Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see if a value or object is in a QuerySet field

Tags:

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.

like image 421
David542 Avatar asked Jul 02 '11 01:07

David542


People also ask

How do I check if a QuerySet exists?

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.

Which can be used to retrieve an object directly instead of a QuerySet?

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.

What is a QuerySet 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.

What does QuerySet filter return?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.


1 Answers

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' 
like image 191
shanyu Avatar answered Oct 16 '22 08:10

shanyu