Django: Get an object form the DB, or 'None' if nothing matches

后端 未结 8 1492
粉色の甜心
粉色の甜心 2020-11-30 02:45

Is there any Django function which will let me get an object form the database, or None if nothing matches?

Right now I\'m using something like:

foo          


        
8条回答
  •  囚心锁ツ
    2020-11-30 03:19

    Whether doing it via a manager or generic function, you may also want to catch 'MultipleObjectsReturned' in the TRY statement, as the get() function will raise this if your kwargs retrieve more than one object.

    Building on the generic function:

    def get_unique_or_none(model, *args, **kwargs):
        try:
            return model.objects.get(*args, **kwargs)
        except (model.DoesNotExist, model.MultipleObjectsReturned), err:
            return None
    

    and in the manager:

    class GetUniqueOrNoneManager(models.Manager):
        """Adds get_unique_or_none method to objects
        """
        def get_unique_or_none(self, *args, **kwargs):
            try:
                return self.get(*args, **kwargs)
            except (self.model.DoesNotExist, self.model.MultipleObjectsReturned), err:
                return None
    

提交回复
热议问题