Home  >  Q&A  >  body text

python - django model uses get or filter

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

reply all(3)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-06-12 09:23:33

    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

    reply
    0
  • 阿神

    阿神2017-06-12 09:23:33

    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

    reply
    0
  • PHP中文网

    PHP中文网2017-06-12 09:23:33

    The efficiency of using filter.first is the same and no exception will be thrown

    reply
    0
  • Cancelreply