Django Queryset对反向外键进行过滤 [英] Django Queryset with filtering on reverse foreign key

查看:427
本文介绍了Django Queryset对反向外键进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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 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 Makes and each one's related MakeContents 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆