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.
exists(): .... Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.
Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With