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

查看:34
本文介绍了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 和每个相关 MakeContent 的查询集,其中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两个数据库查询.第一个是抓取所有包含MakeContentsMakeContents,其中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天全站免登陆