Django Queryset对反向外键进行过滤 [英] Django Queryset with filtering on reverse foreign key
问题描述
我有以下Django模型:
I have the following Django model:
class Make:
name = models.CharField(max_length=200)
class MakeContent:
make = models.ForeignKey(Make)
published = models.BooleanField()
我想知道是否可以(不需要直接编写SQL)来生成包含所有 Make $ c $的查询集c> s和每个人的相关的
MakeContent
s published = True
。
I'd like to know if it's possible (without writing SQL directly) for me to generate a queryset that contains all Make
s and each one's related MakeContent
s where published = True
.
推荐答案
Django不支持用于反向外键查找的select_related()方法,所以在不离开Python的情况下,最好的方法是两个数据库查询。第一个是抓住包含MakeContents的所有Makes,其中published = True,第二个是抓取所有的MakeContents,其中published = True。然后,您必须循环并排列数据。以下是有关如何执行此操作的好文章:
Django doesn't support the select_related() method for reverse foreign key lookups, so the best you can do without leaving Python is two database queries. The first is to grab all the Makes that contain MakeContents where published = True, and the second is to grab all the MakeContents where published = True. You then have to loop through and arrange the data how you want it. Here's a good article about how to do this:
http://blog.roseman.org.uk/2010/01/11/django-patterns-part-2-efficient-reverse-lookups/
这篇关于Django Queryset对反向外键进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!