如何继承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)
blog
现在显然是一个Content对象。
如果我输入Catalog.active.get(pk = 1)我想要一个Content对象但是
如果我键入BlogCatalog.active.get(pk = 1),我想要一个BlogCatalog对象。
如何在不浪费的情况下实现这一目标?
答案 0 :(得分:2)
Django只允许从抽象基类继承Manager。要将同一个经理用作非ABC,您必须明确声明它。
查看django docs on custom managers and inheritance。
基本上,只需这样做:
class BlogCatalog(Content):
frequency = models.PositiveSmallIntegerField(max_length=2, choices=make_index_based_tuple(l=FREQUENCY), verbose_name='Frequenz',)
active = ContentActiveManager()
希望有所帮助。
答案 1 :(得分:0)
我想出的唯一方法:
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