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.filter(...).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
getmethod of the manager:The
existsmethod is applicable also, if you don’t need to get the object:If you already have the object and want to determine if it is contained in a queryset:
If you want to use a value instead of an object: