[Django]-How to see if a value or object is in a QuerySet field

52👍

✅

Simplest way is to use the get method of the manager:

try:
    foo = Foo.objects.get(foo_name='David')
except Foo.DoesNotExist:
    print 'Nope'
except Foo.MultipleObjectsReturned:
    print 'Filter is a better choice here'

The exists method is applicable also, if you don’t need to get the object:

if Foo.objects.filter(foo_color='green').exists():
    print 'Nice'

If you already have the object and want to determine if it is contained in a queryset:

foo = Foo.objects.get(foo_name='David')
qs = Foo.objects.filter(<criteria>)
if foo in qs:
    print 'Nice again'

If you want to use a value instead of an object:

value = 'David'
qs = Foo.objects.filter(<criteria>).values_list('foo_name',flat=True)
if value in qs:
    print 'Nice'

1👍

in Django >= 4.0, contains(obj) can be used, that is faster

if some_queryset.contains(obj):
    print('Entry contained in queryset')

The documentation also says this is faster than the following.

if obj in some_queryset:
    print('Entry contained in queryset')

Leave a comment