假设每件衣服都只有一种颜色,但同一种颜色可以出现在不同衣服上,这样颜色和衣服就是一对多关系,Django 中的一对多关系用 ForeignKey 来实现。
from django.db import models
class Colors(models.Model):
colors = models.CharField(max_length=10)
def __str__(self):
return self.colors
# 一对多
class Clothes(models.Model):
#与颜色表为外键,颜色表为母表
clothes_color = models.ForeignKey("Colors")
description = models.CharField(max_length = 10) #描述
def __str__(self):
return self.description
查询数据
子表查询母表:
# 查询某件衣服的颜色
# 方法一
clothes_obj = Clothes.objects.get(description="毛衣")
clothes_obj.clothes_color.colors
>>> 'red'
# 方法二
colors_obj = Colors.objects.get(clothes__description="毛衣")
colors_obj.colors
>>> 'red'
母表查询子表:
# 查询红色的衣服有哪些
# 方法一
colors_obj = Colors.objects.get(colors="red")
colors_obj.clothes_set.all()
>>> <QuerySet [<Clothes: 毛衣>, <Clothes: 衬衫>]>
# 方法二
colors_obj = Colors.objects.get(colors="red")
Clothes.objects.filter(clothes_color=colors_obj)
>>> <QuerySet [<Clothes: 毛衣>, <Clothes: 衬衫>]>
# 方法二简便写法
Clothes.objects.filter(clothes_color__colors="red")
>>> <QuerySet [<Clothes: 毛衣>, <Clothes: 衬衫>]>
#写法3
# 通过母表获取到颜色为红的 id
color_id = Colors.objects.get(colors="red").id
Clothes.objects.filter(clothes_color_id=color_id)
>>> <QuerySet [<Clothes: 毛衣>, <Clothes: 衬衫>]>
增删数据
添加
# 方法一
colors_obj = Colors.objects.get(colors="green")
Clothes.objects.create(clothes_color=colors_obj, description="外套")
# 方法二
colors_obj = Colors.objects.get(colors="green")
clothes_obj = Clothes(clothes_color=colors_obj, description="棉袄")
clothes_obj.save()
删除
# 对象和 QuerySet 都有方法 delete()
Clothes.objects.get(description="棉袄").delete()
Colors.objects.filter(colors="green").delete()
修改数据
# 把颜色为红色的衣服的描述全改为“红色衣服”
# 方法一
clothes_obj = Clothes.objects.filter(clothes_color__colors="red")
clothes_obj.update(description="红色衣服")
# 方法二
color_id = Colors.objects.get(colors="red").id
clothes_obj = Clothes.objects.filter(clothes_color_id = color_id)
clothes_obj.update(description="红色衣服")