Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django model manager or django queryset

I was reading django docs and these two classes seemed similar,

here is the sample from django docs:

class PersonQuerySet(models.QuerySet):
    def authors(self):
        return self.filter(role='A')

    def editors(self):
        return self.filter(role='E')

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

    def authors(self):
        return self.get_queryset().authors()

    def editors(self):
        return self.get_queryset().editors()

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    role = models.CharField(max_length=1, choices=(('A', _('Author')), ('E', _('Editor'))))
    people = PersonManager()

In the sample code as you can see code in PersonQuerySet can be moved to PersonManager (or move manager to query set) - my point is I can merge one to another without any problem)

so what is the difference between manager and queryset? do they have different use cases? or should I simply use one of them and ignore existance of the other one?

like image 229
aliva Avatar asked Oct 27 '25 09:10

aliva


1 Answers

You can now use the from_queryset() method on you manager to change its base Queryset.

This allows you to define your Queryset methods and your manager methods only once

from the docs

For advanced usage you might want both a custom Manager and a custom QuerySet. You can do that by calling Manager.from_queryset() which returns a subclass of your base Manager with a copy of the custom QuerySet methods:

class PersonQuerySet(models.QuerySet):
    def authors(self):
        return self.filter(role='A')

    def editors(self):
        return self.filter(role='E')

class BasePersonManager(models.Manager):
    pass

PersonManager = BasePersonManager.from_queryset(PersonQuerySet)

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    role = models.CharField(max_length=1, choices=(('A', _('Author')), ('E', _('Editor'))))
    people = PersonManager()
like image 80
maazza Avatar answered Oct 29 '25 00:10

maazza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!