Django ORM中的双重反向过滤 [英] Double reverse filtering in Django ORM

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

问题描述

我在过滤数据时面临一个问题.

I am facing one issue while filtering the data .

我有三个模型...

class Product:
   size = models.CharField(max_length=200)

class Make(models.Model):
    name = models.ForeignKey(Product, related_name='product_set')

class MakeContent(models.Model):
    make = models.ForeignKey(Make, related_name='make_set')
    published = models.BooleanField()

我可以生成一个查询集,其中包含所有Make以及每个人的相关MakeContent,其中发布的内容为True.

I can generate a queryset that contains all Makes and each one's related MakeContents where published = True.

Make.objects.filter(make_set__published=True)

我想知道是否有可能(无需直接编写SQL)生成一个查询集,该查询集包含所有Product和每个人的相关MakeContent,发布时为True.

I'd like to know if it's possible (without writing SQL directly) for me to generate a queryset that contains all Product and each one's related MakeContents where published = True.

我已经尝试过了

Product.objects.filter(product_set__make_set__published=True)

但是它不起作用

推荐答案

子查询可以解决问题.

from django.db.models import Subquery

sub_query = MakeContent.objects.filter(published=True)

Product.objects.filter(
    pk__in=Subquery(sub_query.values('make__name__pk'))
)

这篇关于Django ORM中的双重反向过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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