Django:使用自定义管理器从基本模型继承的模型。管理者可以有动态变量吗?

发布于 2024-08-19 14:17:23 字数 643 浏览 2 评论 0原文

我需要让我的所有模型继承这个管理器(还没有测试过这个管理器,它可能很荒谬,所以我也完全接受建议/批评):

class AccountFilterManager(models.Manager):
    def __init__(self, account=None, *args, **kwargs):
        super(AccountFilterManager, self).__init__(*args, **kwargs)
        self.account = account  # account of course will be an instance of Account(models.Model)

    def get_query_set(self):
        if self.account:
            return super(AccountManager,self).get_query_set().filter(account=self.account)

你可以看到我正在尝试做什么。限制根据我正在处理的帐户过滤掉所有地方的需要。

让该经理使用我的所有模型的最佳方法是什么?抽象基础模型有吗?另外,我如何从视图级别将帐户变量传递到其中?难道这一切都是错误和邪恶的吗?一周以来我一直在努力寻找一种方法来克服这个问题:(。

I need to have all my models inherit this manager (Haven't tested this manager and it may be ridiculous so I'm completely open to suggestion/criticism on it as well):

class AccountFilterManager(models.Manager):
    def __init__(self, account=None, *args, **kwargs):
        super(AccountFilterManager, self).__init__(*args, **kwargs)
        self.account = account  # account of course will be an instance of Account(models.Model)

    def get_query_set(self):
        if self.account:
            return super(AccountManager,self).get_query_set().filter(account=self.account)

You can see what I'm trying to do. limit the need to filter out everywhere based on what account I'm dealing with.

What would be the best way to get this manager to work with all my models? Abstract base model with it? Also, how am I going to pass in the account variable into it from the view level? Is this all wrong and evil? I've been trying to find a way to conquer this for a week now :(.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绅刃 2024-08-26 14:17:23

不会。管理器被实例化为类属性,从而为所有模型实例提供相同的管理器。

No. The manager is instantiated as a class attribute, thereby giving all model instances the same manager.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文