Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to specify empty queryset to not empty queryset : [ ] to [<object: hi>]

Tags:

python

django

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...

like image 846
gadss Avatar asked Jan 19 '26 09:01

gadss


2 Answers

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"
like image 177
Yuji 'Tomita' Tomita Avatar answered Jan 21 '26 01:01

Yuji 'Tomita' Tomita


This should work

if not x:
    print "Empty"
else:
    print data`
like image 36
kamasheto Avatar answered Jan 21 '26 01:01

kamasheto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!