【问题标题】:Django-model-utils: Use InheritanceManager with custom querysetsDjango-model-utils:将 InheritanceManager 与自定义查询集一起使用
【发布时间】:2014-02-24 19:13:53
【问题描述】:

我使用 django-model-utils 作为 InheritanceManager 类,因此我的父模型 Activity 的查询集也从它们的子类返回信息,例如 Sports、Party 等。

但是,现在我想进行自定义查询以默认添加一些过滤器,但我无法让它对 InheritanceManager 起作用。由于 InheritanceManager 已经替换了我模型的默认管理器,因此我无法按照Django's docs 的描述创建自定义管理器。

简单地从 InheritanceManager 继承自定义管理器是行不通的。还有其他想法吗?

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    当然可以,只需定义您自己的继承自 InheritanceManager 的自定义管理器类,如下所示:

    from model_utils.managers import InheritanceManager
    
    class CustomInheritanceManager(InheritanceManager):
        def get_queryset(self):
            # your custom queryset here ...
    
    class YourModel(models.Model):
        objects = CustomInheritanceManager()
    

    【讨论】:

    • 我可以发誓我之前已经尝试过这个确切的解决方案(即使使用get_queryset 而不是get_query_set),但它没有奏效。现在可以了,非常感谢!
    • 我习惯于自定义管理器默认做一些注释,但这搞砸了模型的保存功能,因为注释值在保存时被视为合法的数据库列。所以我的代码毕竟没有工作。太糟糕了。
    猜你喜欢
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多