Inheriting django ModelManager

How do I inherit ModelManager?

class Content(models.Model):
    name = models.CharField(max_length=255, verbose_name='Name des Blogs')
    slug = models.SlugField(max_length=80, blank=True)
    objects = models.Manager()
    active = ContentActiveManager()

class ContentActiveManager(models.Manager):
    def get_query_set(self):
        return super(ContentActiveManager,self).get_query_set().filter(activated=True,show=True)

class BlogCatalog(Content):
    frequency = models.PositiveSmallIntegerField(max_length=2, choices=make_index_based_tuple(l=FREQUENCY), verbose_name='Frequenz',)



blog = BlogCatalog.active.get(pk=1)

blognow, obviously, is a Content object. If I type Catalog.active.get (pk = 1), I want a Content object, but If I find BlogCatalog.active.get (pk = 1), I want a BlogCatalog object.

How can I achieve this without being redundant?

+3
source share
2 answers

Django only allows manager inheritance from an abstract base class. To use the same manager as non-ABC, you must explicitly declare it.

Check out the django docs for custom managers and inheritance .

Basically, just do the following:

class BlogCatalog(Content):
    frequency = models.PositiveSmallIntegerField(max_length=2, choices=make_index_based_tuple(l=FREQUENCY), verbose_name='Frequenz',)
    active = ContentActiveManager()

Hope this helps.

+2
source

, :

class Content:

    @staticmethod
    def __new__(cls, *args, **kwargs):
        super_new = super(Content, cls).__new__(cls, *args, **kwargs)
        cls.add_to_class('active', ContentActiveManager())
        return super_new
0

Source: https://habr.com/ru/post/1722306/


All Articles