As shown in the following code, the instance object will be obtained based on the instance ID. As we all know, if the ID does not exist when getting, an exception will occur, but the filter will not.
So, I would like to ask everyone, in a situation like this, is it better to use get and handle the exception, or is it better to use filter to do it better? Which one is more standardized?
def get_city_image(self, instance):
if instance.city_id:
try:
city_image = City.objects.get(id=instance.city_id).image.url
# city_image = City.objects.filter(id=instance.city_id).last().image.url
except Exception, e:
city_image = None
else:
city_image = None
return city_image
Framework selection and design issues, Django throws exceptions, other frameworks directly return None, it depends on which one you like, I don’t like this kind of throwing exceptions directly, just make up your own method
Reference link: django extension/patch QuerySet
The efficiency of using filter.first is the same and no exception will be thrown