python - 如何将自定义模型管理器设置为 Django 中的默认模型管理器?
问题描述
我在 Django 项目中有多个应用程序和模型。现在我想在所有应用模型中使用自定义模型管理器。我不想query
在每个模型中编写自定义模型管理器。我只想知道是否可以将自定义模型管理器设置为所有应用程序的默认模型管理器?
管理器.py
class CustomQuerySet(models.Manager):
def get_queryset(self):
return super(CustomQuerySet, self).get_queryset().filter(status=True)
解决方案
您可以设置一个抽象模型并在所有模型中继承它:
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...
推荐阅读
- vba - mailItem.Recipients[i].Address 返回的值代表什么?
- ios - resignFirstResponder() 的模糊使用
- azureservicebus - 如何查看 Azure 服务总线的用户错误日志?
- java - 即使在 Ubuntu 中安装后 Java 也无法运行
- azure - 将 Azure API for FHIR 数据复制到 datalake
- c++ - 从类方法调用朋友函数
- nginx - 启用 ssl 时,nginx 不再重写重定向位置
- python - 测试目录中的 Python 导入
- html - 我想在点击时使用 javascript 或 jquery 将动画播放状态更改为运行。任何帮助都会得到帮助
- javascript - 如何尽快运行 JavaScript 函数?