2

i have a problem in determining an object if it is empty or not... here is my code :

this value has no data

>>> x = Booking.objects.filter(date_select='2011-12-3')
>>> print x
[]
>>> if x == None:
...  print 'none'
... 
>>> 

this has a data :

>>> x = Booking.objects.filter(date_select='2011-12-2')
>>> print x
[<Booking: arab>, <Booking: arab>, <Booking: vvv>]
>>> if x == None:
...  print 'none'
... 
>>>

I have learned that [] is not equal to None from my prev question... Here is the algorithm that i want to apply in my code:

if x has an empty queryset
 print empy
else
 print data

can anyone can help me about it? thanks...

gadss
  • 21,687
  • 41
  • 104
  • 154
  • In the [previous question](http://stackoverflow.com/q/8365090), the problem probably was that you were using `if x:` to see if the list is empty. However, a non-empty list is _not_ falsy - on the contrary, it is truish, and you would only enter in the `if` if the list was not empty. The simple, quick'n'dirty solution is to negate the list: instead of `if x:` write `if not x:`. However, @Yuji solution below seems far better because more efficient. Just remember to negate the return of exists: `if my_queryset.exists(): print "empty list"`. – brandizzi Dec 03 '11 at 04:04
  • This and the previous question are really just basic Python. Please go and do an introductory Python tutorial. – Daniel Roseman Dec 03 '11 at 08:18

3 Answers3

9

Use 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. This means that calling QuerySet.exists() is faster than bool(some_query_set), but not by a large degree.

if my_queryset.exists():
    print "QuerySet has Data"
else:
    print "QuerySet is empty"
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
2

This should work

if not x:
    print "Empty"
else:
    print data`
kamasheto
  • 1,020
  • 6
  • 12
0

try

x = Booking.objects.filter(date_select='2011-12-2')
if x.count() == 0:
    print "empty"
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178