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.
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 atryblock, catch the relevant exceptions, and handle appropriately.