- 先上示例模型
- 一對一的情況
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屬性類似上面
隨手記錄,不足之處請多指教!!!
