How to check if an element is present in a Django queryset?
Solution 1
You can use the following code:
if e in Entry.objects.all():
#do something
Or the best approach:
if Entry.objects.filter(id=e.id).exists():
#do something
Solution 2
The best approach, according to Django documentation: https://docs.djangoproject.com/en/2.1/ref/models/querysets/#exists
if Entry.objects.filter(id=item.id).exists():
# Do something
But you can also do:
if item in Entry.objects.all():
# Do something
Although this approach is the worser as possible. Because it will loop over the whole Queryset pulling elements from the database one by one, compared to the other approach that is almost everything done in the Database level.
If you have a list of ids or a Queryset others approaches would be use __in
Example with a Queryset:
query_ids = other_queryset.values_list('field_id', flat=True)
if Entry.objects.filter(id__in=query_ids).exists():
# Do something
Or if you have a list of ids:
if Entry.objects.filter(id__in=[1, 2, 3, 4, 5]).exists():
# Do something
Keep in mind that every time that you do len(queryset)
, item in queryset
or list(queryset)
you decrees heavily the performance of Django. I already see cases where by avoiding this practices We improved dozens of seconds in an application.
Solution 3
You can use in
operator:
entry_set = Entry.objects.all()
if an_entry in entry_set:
# The element present.
Related videos on Youtube
Brian
Updated on February 28, 2020Comments
-
Brian about 4 years
Is it like a regular python set?
Suppose I have the following queryset
entry_set = Entry.objects.all()
How do I check if Entry Object e is present in entry_set?
-
Brian over 8 yearsWhat if I have an Entry title instead of Entry object and want to check if that title exists in queryset?
-
awesoon over 8 years@Brian, you could do something like
Entry.objects.filter(title='Your awesome title').exists()
-
Lucas Wieloch almost 5 years
Entry.objects.filter(id__in=[1, 2, 3, 4, 5]).exists()
will returnTrue
if at least one element of the list is inside the queryset -
Alex Griffith almost 3 yearsusing .exists() will prevent you from bringing in extra values if you can't filter off a unique key. It can also be used directly in the if statement, saving use of a variable. e.g. 'if Entry.objects.filter(id=e.id).exists(): ... do something here '
-
lbris about 2 yearsNow in Django 4.0 you can use contains() method instead, if you ave already fetched the Queryset : docs.djangoproject.com/fr/4.0/ref/models/querysets/#contains