python - django model uses get or filter
女神的闺蜜爱上我
女神的闺蜜爱上我 2017-06-12 09:21:33
0
3
872

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
女神的闺蜜爱上我
女神的闺蜜爱上我

reply all(3)
淡淡烟草味
def get_city_image(self, instance):
    try:
        city_image = City.objects.get(id=instance.city_id).image.url
    except City.DoesNotExist:
        #捕获City不存在的异常, 抛出异常或是自己处理
        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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template