Prometheus
Prometheus

Reputation: 33625

Django check an object has results

I want to check if an object returns a value in my views.py this is my code...

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

So, I was thinking something like this...

  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.

what is the best way to approach this.

Upvotes: 0

Views: 107

Answers (2)

akotian
akotian

Reputation: 3935

You can also try:

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

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

As the documentation states, .get() will always either return a single model, or it will raise one of two exceptions. Simply put the call in a try block, catch the relevant exceptions, and handle appropriately.

Upvotes: 1

Related Questions