Django ORM:使用具有“和"功能的对象列表进行过滤 [英] Django ORM: filter using a list of objects with an 'and' functionality

查看:118
本文介绍了Django ORM:使用具有“和"功能的对象列表进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新手问题...

型号:

Item(model.Models):
    ...
    attributes = models.ManyToManyField('Attributes', null=True)
    ...


Attributes(models.Models):
    title = models.CharField(max_length=100, unique = True)
    value = models.TextField()
    ...

我有一个在过滤Item表时要使用的属性对象[attObj1, attobj2, attObj3, attObjN]的列表.以下查询有效.

I have a list of attribute objects [attObj1, attobj2, attObj3, attObjN] that I want to use when filtering the Item table. The following query works.

items = Item.objects.filter(attributes = attObj1 and attObj2 and attObj3)

问题 :由于列表中的属性数量未知,我需要动态创建查询(即:attObj1 and attObj2 and attObj3... and attObjN).

我尝试使用以下复杂查询集没有运气(

I tried using the following complex queryset with no luck (source). It returned an empty list.

attList = [attObj1, attObj2, attObj3]
query = Q(attributes = attList.pop(0))
for att in attList:
    query = query & Q(attributes=att)

items = Item.objects.filter(query)

这可能吗?

推荐答案

您可以尝试:

items = Item.objects.filter(attributes__in=attList)

您也可以尝试链接/多个过滤器

You can also try chaining/multiple the filters

attList = [attObj1, attObj2, attObj3]
fitems = Items.objects.filter()
for att in attList:
     fitems = fitems.filter(attributes=att)

fitems简化为一个包含对象的集合,这些对象在attList中具有属性.

fitems are reduced to a set containing objects which have attributes in attList.

这篇关于Django ORM:使用具有“和"功能的对象列表进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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