How would I see if a value is in a QuerySet?
For example, if I have the following model:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
first_name = models.CharField(max_length=50)
How would I find out if the first_name 'David' is contained in a QuerySet? A way to do the following:
ld = UserProfile.objects.filte开发者_如何学运维r(...).values('first_name')
>>> for object in ld:
... if object['first_name'] =='David':
... print True
Or if a particular user object is instead? Something like 'David' in QuerySet['first_name']
? Thank you.
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'
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')
精彩评论