how to specify values in objects in django: is []

2019-09-08 06:43发布

how can i specify or determine the values in my objects in python if it has this value [] or it has [<Booking: arab>], let us say that in my queryset, i filter a value that not exist in my objects.

here is what i have done : this date_select has no data

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

is it [] not equal to None? when i try a date_select that has data

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

i just want to determine if x has a data or not... can anyone can give me an idea about my case?

thanks in advance

3条回答
叼着烟拽天下
2楼-- · 2019-09-08 07:00

No, [] is not equal to None. [] is an empty list - a list with no content but that exists nonetheless and can come to have some elements. None is a value representing "nothing" - when you find the None value, it meas something like "this variable has no relevant content". Since empty lists can be relevant content - for example, the empty list can be the initial state of a list which will accumulate elements over time - then there is no sense in assuming that [] == None.

armonge gave you the response: just use the list as the condition, because empty lists are "falsy" - that is, empty lists has the same effect of False when used as a condition for an if, while etc. If you want to execute something when the list does not have some content, just negate it:

if not x:
    print 'empty list (is not None)'

BTW, a question: are you used to program in Lisp? This is the only language where an empty list is equivalent to the "None type" (in this case, nil).

查看更多
Emotional °昔
3楼-- · 2019-09-08 07:14

You just need

if queryset:
    print 'not empty'
查看更多
Anthone
4楼-- · 2019-09-08 07:17

If you want to know if your queryset returned any results, call the exists method.

x = Booking.objects.filter(date_select='2011-12-3')
if x.exists():
   # There are some results from this query set

If you want to know how many items, you can use count

x = Booking.objects.filter(date_select='2011-12-3')
print x.count()
查看更多
登录 后发表回答