django模型的过滤管理器,由用户定制
我有一个模型,像这样:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于管理器只是方法,因此您可以在那里传递任何您想要的内容:
虽然效率不是很高,但它可以完成工作。
Since managers are just methods, you can pass whatever you want there:
Though not very efficient, it does the job.
这看起来很像 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_permissionsMaybe you can take a look at how they implemented that feature?