Django使用详解:ORM 的反向查找(related_name)
先定义两个模型,一个是A,一个是B,是一对多的类型。
classA(models.Model): name=models.CharField('名称',max_length=32) classB(models.Model): a=models.ForeignKey(A,verbose_name='A类',related_name="test") name=models.CharField('称呼',max_length=16)
如果我们要查询一个A拥有哪些B的话,那我们要怎么做呢
通过主表来查询子表
A.objects.get(id=A_id).test.all().order_by('-created'),
django默认每个主表的对象都有一个是外键的属性,可以通过它来查询到所有属于主表的子表的信息。这个属性的名称默认是以子表的名称小写加上_set()来表示(上面默认以b_set访问),默认返回的是一个querydict对象。
related_name可以给这个外键定义好一个别的名称
通过子表来查询主表
B.objects.filter(a=A_id).order_by('-created')
以上这篇Django使用详解:ORM的反向查找(related_name)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。