Django检查一个对象有结果

时间:2013-02-02 14:52:27

标签: python django

我想检查一个对象是否在我的views.py中返回一个值,这是我的代码......

  city = City.objects.get(name=form.cleaned_data['autocompleteCity'])

所以,我在想这样的事情......

  city = City.objects.get(name=form.cleaned_data['autocompleteCity'])

  if city:
     #we have results do something with city object
   else: 
     #no results display error and stop processing form.

解决这个问题的最佳方式是什么。

2 个答案:

答案 0 :(得分:1)

作为the documentation states.get()始终返回单个模型,否则会引发两个异常中的一个。只需put the call in a try block, catch the relevant exceptions, and handle appropriately

答案 1 :(得分:1)

您也可以尝试:

city = City.objects.filter(name=form.cleaned_data['autocompleteCity'])

if city.count():
   # if you are expecting only one record to be returned, you can access the first record
   # Else you will have to iterate through the result set returned
   print city[0]         
else:
   #no records present
   pass