如下面代码,会根据实例ID获取实例对象,大家知道get的时候如果id不存在会出现异常,但是filter不会。
那么,请问大家,像类似这种情况是用get然后处理异常要好呢,还是filter来做好呢,哪种更规范?
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