Django object multiple exclude()

限于喜欢 提交于 2019-12-18 14:27:00

问题


Is there a way to do a query and exclude a list of things, instead of calling exclude multiple times?


回答1:


Based on your reply to Ned, it sounds like you just want to exclude a list of tags. So you could just use the in filter:

names_to_exclude = [o.name for o in objects_to_exclude] 
Foo.objects.exclude(name__in=names_to_exclude)

Does that do what you want?




回答2:


What's wrong with calling exclude multiple times? Queries are lazy, nothing happens until you try to pull data from it, so there's no downside to using .exclude() more than once.




回答3:


You can do it pretty easily with the Q object:

from django.db.models import Q

excludes = None
for tag in ignored_tags:
    q = Q(tag=tag)
    excludes = (excludes and (excludes | q)) or q # makes sure excludes is set properly
set_minus_excluded = Foo.objects.exclude(excludes)

You should also be able to do it dynamically with exclude():

qs = Foo.objects.all()
for tag in ignored_tags:
    qs = qs.exclude(tag=tag)



回答4:


To improve on Daniel Roseman's answer I think it would be better to get the values you need directly from the queryset instead of the for loop that could be expensive on large data sets i.e.

names_to_exclude = objects_to_exclude.values_list('name')
Foo.objects.exclude(name__in=names_to_exclude)



回答5:


You can try this also.

exclude_list = ['A', 'B', 'C'] qs = Foo.objects.exclude(items__in=exclude_list)



来源:https://stackoverflow.com/questions/912540/django-object-multiple-exclude

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