一对一对应:
class A(models.Model):
name = models.CharField("姓名", max_length=11)
class B(models.Model):
name = models.CharField("姓名", max_length=11)
author = models.OneToOneField(A,on_delete=models.CASCADE)
on_delete:
⑴ models.CASCADF 级联删除
⑵ models.PROTECT 删除报错
⑶ SET_NULL 删除后ForeignKey null ;需要null=True
⑷ SET_DEFAULT ForeignKey设置默认值,删除后为默认值
创建数据
无外键
a1=A.objects.create(name='wang')
有外键
⑴B.objects.create(name='wang',a=a1)#对应主键的obj
⑵B.objects.create(name='wang',a_id=1)#对应主键的值
查询数据
1正向查询
from .models import B
b1=B.objects.get(name="wang")
print(b1.author.name)
2反向查询
b1 = B.objects.get(name="wang")
print(b1.wife.name)
一对多:
class A(models.Model):
name = models.CharField("姓名", max_length=11)
class B(models.Model):
name = models.CharField("姓名", max_length=11)
author = models.ForeignKey(A,on_delete=models.CASCADE)
创建数据
无外键
a1=A.objects.create(name='wang')
有外键
⑴B.objects.create(name='wang',a=a1)#对应主键的obj
⑵B.objects.create(name='wang',a_id=1)#对应主键的值
查询数据
1正向查询
from .models import B
b1=B.objects.get(name="wang")
print(b1.author.name)
2反向查询
b1 = B.objects.get(name="wang")
names= b1.a_set.all() #name_set 多表表名_set
for name in names:
print(name.title)
多对多:
class A(models.Model):
name = models.CharField("姓名", max_length=11)
class B(models.Model):
name = models.CharField("姓名", max_length=11)
author = models.ManyToManyField(A)
创建数据
创建A表数据
a1=A.objects.create(name='wang')
B表创建数据,并关联A
b1=a1.b_set.create(name='python') #name_set 多表表名_set
再创建A表数据
a2=A.objects.create(name='pang')
加入B表之前的键中
a2.b_set.add(b1)
查询数据
参考一对多
框架可直接(关联models的类名小写__字段名)进行查询:
A.objects.create(b__name="python")
B.objects.create(a__name="pang")