57
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?
11
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.
- [Django]-How to send a POST request using django?
- [Django]-How does Django Know the Order to Render Form Fields?
- [Django]-Django error when installing Graphite – settings.DATABASES is improperly configured. Please supply the ENGINE value
8
You can try this also.
exclude_list = ['A', 'B', 'C']
qs = Foo.objects.exclude(items__in=exclude_list)
- [Django]-What are the best practices to use AngularJS with Django
- [Django]-What is the best way to access stored procedures in Django's ORM
- [Django]-Many-To-Many Fields View on Django Admin
5
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)
- [Django]-How do I remove Label text in Django generated form?
- [Django]-How to access my 127.0.0.1:8000 from Android tablet
- [Django]-How to write setup.py to include a Git repository as a dependency
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)
- [Django]-CORS error while consuming calling REST API with React
- [Django]-How can I check database connection to mysql in django
- [Django]-Session database table cleanup
Source:stackexchange.com