Reputation: 6693
here is my code
for add in Address.objects.filter(city_id='112'):
print add
if add:
print 'ok,I got something'
else:
print 'nothing found'
When it filter somrthing,it will print :
Address object
ok.Igot something
But when it didn't filter something,
print add
show nothing,and it didn't print 'nothing found'
I want to ask how to check the Address.objects.filter() get object
Upvotes: 0
Views: 44
Reputation:
When Address.objects.filter(city_id='112')
returns an empty array, your for
loop is skipped entirely. Your if
is inside that loop, so when nothing is returned, no other code is hit at all.
Upvotes: 0
Reputation: 45575
In boolean context queryset returns True
if it is not empty and False
is nothing is found:
address_list = Address.objects.filter(city_id='112')
if address_list:
print 'ok,I got something'
for address in address_list:
print address
else:
print 'nothing found'
If you use queryset in the template then the {% for %} ... {% empty %} template tag can help you:
<ul>
{% for address in address_list %}
<li>{{ address }}</li>
{% empty %}
<li>Nothing found</li>
{% endfor %}
</ul>
Upvotes: 3