Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 如何连锁模型经理?_Django_Django Models - Fatal编程技术网

Django 如何连锁模型经理?

Django 如何连锁模型经理?,django,django-models,Django,Django Models,我有两个抽象模型: class SoftDeleteModel(models.Model): objects = SoftDeletableManager() class Meta: abstract = True class BookAwareModel(models.Model): book = models.ForeignKey(Book) class Meta: abstract = True 我经常将这些模型用于

我有两个抽象模型:

class SoftDeleteModel(models.Model):
    objects = SoftDeletableManager()

    class Meta:
        abstract = True


class BookAwareModel(models.Model):
    book = models.ForeignKey(Book)

    class Meta:
        abstract = True
我经常将这些模型用于干燥目的,例如:

class MyNewModel(SoftDeleteModel, BookAwareModel):
SoftDeleteModel
有一个自定义管理器
SoftDeleteTableManager()

如果我想扩展
BookAware
抽象模型,在
Books
上添加一个queryset过滤器,同时仍然保留
SoftDeletableManager()
我该如何做


例如,我无法将
objects=BookManager()
添加到
BookAwareModel
中,因为它将覆盖
SoftDeletableManager

在对您的代码进行了一些处理后,我提出了三种可能的解决方案(根据我的测试):

选项1

创建一个组合管理器,用于定义具体的MyNewModel并将其用于该模型:

class CombiManager(SoftDeletableManager, BookAwareManager):

    def get_queryset(self):
        qs1 = SoftDeletableManager.get_queryset(self)
        qs2 = BookAwareManager.get_queryset(self)
        return qs1.intersection(qs2)
然后

class MyNewModel(SoftDeleteModel, BookAwareModel):

    objects = CombiManager()
选项2:

为BookAware模型创建一个管理器,作为SoftDeleteableManager的子类

class BookAwareManager(SoftDeletableManager):

    def get_queryset(self):
        return super().get_queryset().filter(your_filter)
然后使用与“对象”不同的名称将其添加到您的
BookAware
模型中:

class BookAwareModel(models.Model):
    book = models.ForeignKey(Book)
    book_objects = BookAwareManager()

    class Meta:
        abstract = True
允许您获得过滤后的查询集,如

MyNewModel.book_objects.all()
选项3


将BookAwareManager作为选项2中的经理放入具体的MyNewModel中。然后,您可以将管理器名称保留为默认的“对象”

您是否可以选择将
BookAwareModel
的管理器定义为
SoftDeletableManager
的子类?
MyNewModel.book_objects.all()