0

我想检查一个对象是否在我的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.

解决此问题的最佳方法是什么。

4

2 回答 2

1

文档所述.get()始终返回单个模型,或者将引发两个异常之一。只需将调用放在一个try块中,捕获相关异常,并适当处理

于 2013-02-02T15:05:02.380 回答
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
于 2013-02-02T15:15:26.847 回答