70👍
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
15👍
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.
- [Django]-Tailwindcss: fixed/sticky footer on the bottom
- [Django]-Can someone explain how contribute_to_class works?
- [Django]-Django {% static 'path' %} in javascript file
4👍
in Django >= 4.0, contains(obj)
is faster than the other methods.
Method 1:
if some_queryset.contains(obj):
print('Object entry is in queryset')
Method 1 above will be faster than the following Method 2 which requires evaluating and iterating through the entire queryset:
Method 2:
if obj in some_queryset:
print('Object entry is in queryset')
- [Django]-Django include template from another app
- [Django]-Model not showing up in django admin
- [Django]-NumPy array is not JSON serializable
3👍
You can use in
operator:
entry_set = Entry.objects.all()
if an_entry in entry_set:
# The element present.
- [Django]-How to save a model without sending a signal?
- [Django]-What are the best practices to use AngularJS with Django
- [Django]-AttributeError: 'ManyRelatedManager' object has no attribute 'add'? I do like in django website but got this error
-1👍
You can just filter the queryset on the basis of a unique key present in the Entry model. Say, that key is id, your code would become:
is_present = Entry.objects.filter(id=e.id)
if is_present:
print "Present"
else:
print "Not Present"
- [Django]-Duplicate column name
- [Django]-How to send html email with django with dynamic content in it?
- [Django]-Django model blank=False does not work?