首页 > 解决方案 > 如何将自定义模型管理器设置为 Django 中的默认模型管理器?

问题描述

我在 Django 项目中有多个应用程序和模型。现在我想在所有应用模型中使用自定义模型管理器。我不想query在每个模型中编写自定义模型管理器。我只想知道是否可以将自定义模型管理器设置为所有应用程序的默认模型管理器?

管理器.py

class CustomQuerySet(models.Manager):
    def get_queryset(self):
        return super(CustomQuerySet, self).get_queryset().filter(status=True)

标签: pythondjangodjango-models

解决方案


您可以设置一个抽象模型并在所有模型中继承它:

class MyProjectAbstractModel(models.Model):
   # regular common models fields come in regularly here
   
   objects = models.Manager() # you can specify the built-in or not, for readbilty I like to do so, you can also set your manager to the objects attribute
   my_custom_manager = CustomQuerySet() # your manager
   class Meta:
      abstract = True # means migrations won't handle this model

class MyModelInAppOne(MyProjectAbstractModel):
   # your implemntaion... 

推荐阅读