django模型的过滤管理器,由用户定制

发布于 2024-08-24 19:11:14 字数 334 浏览 3 评论 0原文

我有一个模型,像这样:

class Action(models.Model): 
    def can_be_applied(self, user):
        #whatever
        return True

我想覆盖它的默认管理器。但我不知道如何将当前用户变量传递给管理器,所以我必须这样做:

 [act for act in Action.objects.all() if act.can_be_applied(current_user)]

如何通过覆盖管理器来摆脱它?

谢谢。

I have a model, smth like this:

class Action(models.Model): 
    def can_be_applied(self, user):
        #whatever
        return True

and I want to override its default Manager. But I don't know how to pass the current user variable to the manager, so I have to do smth like this:

 [act for act in Action.objects.all() if act.can_be_applied(current_user)]

How do I get rid of it by just overriding the manager?

Thanks.

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

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

发布评论

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

评论(2

清风疏影 2024-08-31 19:11:15

由于管理器只是方法,因此您可以在那里传递任何您想要的内容:

class ActionManager(models.Manager):
     def applied(self, user):
         return [x for x in self.get_query_set().all() if x.can_be_applied(user)]

Action.objects.applied(someuser)

虽然效率不是很高,但它可以完成工作。

Since managers are just methods, you can pass whatever you want there:

class ActionManager(models.Manager):
     def applied(self, user):
         return [x for x in self.get_query_set().all() if x.can_be_applied(user)]

Action.objects.applied(someuser)

Though not very efficient, it does the job.

时光病人 2024-08-31 19:11:15

这看起来很像 django.contrib.auth 中已经实现的内容:http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.get_all_permissions

也许你可以看看他们是如何实现这个功能的?

This looks a lot like what is already implemented in django.contrib.auth: http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.get_all_permissions

Maybe you can take a look at how they implemented that feature?

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