Django Combining AND and OR Queries with ManyToMany Field

社会主义新天地 提交于 2019-12-01 14:37:59

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's filters automatically AND. Q objects are only needed if you're trying to add ORs. Also, the __in query filter will help you out alot.

Assuming users have multiple brands they like and you want to return any brand they like, you should use:

`brand__in=brands`

Where brands is the queryset returned by something like someuser.brands.all().

The same can be used for your search parameters:

`tags__name__in=['80s','comedy']`

That will return things tagged with either '80s' or 'comedy'. If you need both (things tagged with both '80s' AND 'comedy'), you'll have to pass each one in a successive filter:

keywords = ['80s','comedy']
for keyword in keywords:
    qs = qs.filter(tags__name=keyword)

P.S. related_name values should always specify the opposite relationship. You're going to have logic problems with the way you're doing it currently. For example:

brand = models.ForeignKey(User, related_name='brand')

Means that somebrand.brand.all() will actually return Item objects. It should be:

brand = models.ForeignKey(User, related_name='items')

Then, you can get a brands's items with somebrand.items.all(). Makes much more sense.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!