- 先上示例模型
- 一对一的情况
class A(models.Model): name = models.CharField(max_length=30, blank=True) ida = models.CharFileld(max_length=30, blank=True) class B(models.Model): name = models.CharField(max_length=30, blank=True) idb = models.CharField(max_length=30, blank=True) a = models.OneToOneField(to="A", on_delete=models.CASCADE,related_name='a')
a_queryset = A.objects.get(id=1)
b = a_queryset.b
b_queryset = B.objects.get(id=1)
a = b_queryset.a
or
ida = A.objects.filter(id=1).values('a__ida', 'name')
-
- 一对多的情况
class A(models.Model): name = models.CharField(max_length=30, blank=True) ida = models.CharFileld(max_length=30, blank=True) class B(models.Model): name = models.CharField(max_length=30, blank=True) idb = models.CharField(max_length=30, blank=True) a = models.ForeignKey(to="A", on_delete=models.CASCADE,related_name='a')
正查
a_id = B.objects.get(id=1).a
反查
b_id= A.objects.get(id=1).a.all().values()
idb= A.objects.filter(id=1).values('a__idb') 这里的 a ☞ related_name='a'
没有related_name属性时
b_id = A.objects.get(id=1).b_set.all().values() 采用类名小写_set的方式
-
- 多对多的情况
class A(models.Model): name = models.CharField(max_length=30, blank=True) ida = models.CharFileld(max_length=30, blank=True) class B(models.Model): name = models.CharField(max_length=30, blank=True) idb = models.CharField(max_length=30, blank=True) a = models.ManyToManyField(to="A")
b= B.objects.get(nid='1') a= b.a.all() a= A.objects.get(id='1') b= a.b_set.all() 有related_name属性类似上面
随手记录,不足之处请多指教!!!