user13336549
user13336549

Reputation: 11

do django version 2.2 and above support get_by_id method for model managers

class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db)

def get_by_id(self):
    qs = self.get_queryset().filter(id=id)
    if qs.count() == 1:
        return qs.first()
    return None

Upvotes: 1

Views: 78

Answers (2)

user13336549
user13336549

Reputation: 11

NO, django version 1.7 and below will support this methods get_by_id.

versions after 1.7 will not work this.

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476719

Te get_by_id method is defined in your ProductManager, hence the Django version does not matter. Furthermore the logic of the function is valid, but not very efficient, since it makes two queries.

You can implement this more effectively with:

from django.core.exceptions ObjectDoesNotExist, MultipleObjectsReturned

class ProductManager(models.Manager):
    def get_queryset(self):
        return ProductQuerySet(self.model, using=self._db)
    
    def get_by_id(self):
        try:
            return self.get_queryset().get(id=id)
        except (ObjectDoesNotExist, MultipleObjectsReturned):
            return None

Upvotes: 1

Related Questions