django - How to see if a value or object is in a QuerySet field -
how see if value in queryset?
for example, if have following model:
class userprofile(models.model): user = models.foreignkey(user, unique=true) first_name = models.charfield(max_length=50)
how find out if first_name 'david' contained in queryset? way following:
ld = userprofile.objects.filter(...).values('first_name') >>> object in ld: ... if object['first_name'] =='david': ... print true
or if particular user object instead? 'david' in queryset['first_name']
? thank you.
simplest way use get
method of manager:
try: foo = foo.objects.get(foo_name='david') except foo.doesnotexist: print 'nope' except foo.multipleobjectsreturned: print 'filter better choice here'
the exists
method applicable also, if don't need object:
if foo.objects.filter(foo_color='green').exists(): print 'nice'
if have object , want determine if contained in queryset:
foo = foo.objects.get(foo_name='david') qs = foo.objects.filter(<criteria>) if foo in qs: print 'nice again'
if want use value instead of object:
value = 'david' qs = foo.objects.filter(<criteria>).values_list('foo_name',flat=true) if value in qs: print 'nice'
Comments
Post a Comment