Django将AND和OR查询与ManyToMany字段相结合 [英] Django Combining AND and OR Queries with ManyToMany Field

查看:143
本文介绍了Django将AND和OR查询与ManyToMany字段相结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望有人可以帮助我。



我试图找出是否可以构造一个查询,允许我根据ForeignKey字段和ManyToManyField同时从数据库中检索项目。具有挑战性的部分是它需要对多个ManyToMany对象进行过滤。



一个例子有希望使这个更清楚。以下是我的(简化)模型:

  class Item(models.Model):
name = models.CharField max_length = 200)
brand = models.ForeignKey(User,related_name ='brand')
tags = models.ManyToManyField(Tag,blank = True,null = True)
def __unicode __ )
return self.name
class Meta:
orders = ['-id']

class标签(models.Model):
名称= models.CharField(max_length = 64,unique = True)
def __unicode __(self):
return self.name

我想构建一个基于两个条件检索项目的查询:


  1. 由用户上传的用户所关注的项目(在模型中称为品牌)。所以例如,如果一个用户正在跟随派拉蒙用户帐户,我想要所有的品牌=派拉蒙的项目。


  2. 与保存的搜索中的关键字匹配的项目。例如,用户可以制作并保存以下搜索:80年代喜剧。在这种情况下,我想要所有标签都包含80和喜剧的项目。


现在我知道如何独立构建查询。对于#1,它是:

  items = Item.objects.filter(brand = brand)

而对于#2(根据文档):

  items = Item.objects.filter(tags__name ='80s')。filter(tags__name ='comedy')

我的问题是:是否可以将其构造为单个查询,以便我不必将每个查询转换成列表,加入它们并删除重复的命令? p>

挑战似乎是没有办法使用Q对象来构建查询,您需要一个项目的manytomany字段(在这种情况下为标签)来匹配多个值。以下查询:

  items = Item.objects.filter(Q(tags__name ='80s')& Q(tags__name = '喜剧'))

不工作。



(请参阅: https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships



提前感谢您的帮助!

解决方案

经过多次研究,我找不到一种方法将其组合成单个查询,所以我最终将我的QuerySets转换成列表并组合它们。


hoping someone can help me out with this.

I'm trying to figure out whether I can construct a query that will allow me to retrieve items from my db based on a ForeignKey field and a ManyToManyField at the same time. The challenging part is that it will need to filter on multiple ManyToMany objects.

An example will hopefully make this clearer. Here are my (simplified) models:

class Item(models.Model):
    name = models.CharField(max_length=200)
    brand = models.ForeignKey(User, related_name='brand')
    tags = models.ManyToManyField(Tag, blank=True, null=True)
    def __unicode__(self):
        return self.name
    class Meta:
        ordering = ['-id']

class Tag(models.Model):
    name = models.CharField(max_length=64, unique=True)
    def __unicode__(self):
        return self.name

I would like to build a query that retrieves items based on two criteria:

  1. Items that were uploaded by users that a user is following (called 'brand' in the model). So for example if a user is following the Paramount user account, I would want all items where brand = Paramount.

  2. Items that match the keywords in saved searches. For example the user could make and save the following search: "80s comedy". In this case I would want all items where the tags include both "80s" and "comedy".

Now I know how to construct the query for each independently. For #1, it's:

items = Item.objects.filter(brand=brand)

And for #2 (based on the docs):

items = Item.objects.filter(tags__name='80s').filter(tags__name='comedy')

My question is: is it possible to construct this as a single query so that I don't have to take the hit of converting each query into a list, joining them, and removing duplicates?

The challenge seems to be that there is no way to use Q objects to construct queries where you need an item's manytomany field (in this case tags) to match multiple values. The following query:

items = Item.objects.filter(Q(tags__name='80s') & Q(tags__name='comedy')) 

does NOT work.

(See: https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships)

Thanks in advance for your help on this!

解决方案

After much research I could not find a way to combine this into a single query, so I ended up converting my QuerySets into lists and combining them.

这篇关于Django将AND和OR查询与ManyToMany字段相结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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