如何摆脱与组相关的查询?

2024-04-25 23:05:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须重构代码,就像:

视图.py

def some_method(request):
    customers = list()
    if request.session['group'] == "group1":
        foo = foo.objects.filter(blue=True)
    else:
        foo = foo.objects.all()

我有很多if-else语句,我想使用django内置权限、auth功能来减少这些语句。有什么帮助吗?你知道吗


Tags: 代码py视图ifobjectsfoorequestdef
1条回答
网友
1楼 · 发布于 2024-04-25 23:05:30

我建议您阅读:Using the Django authentication system,特别是:The permission_required decorator部分。你知道吗

在那里你会发现你可以像这样重构你的函数:

@permission_required('some.permission.only.group1.has')
def some_method(request):
    customers = list()
    foo = foo.objects.filter(blue=True)

对于用户不在group1中的情况,应该存在另一个视图。你发布的例子并没有真正说明每个案例都需要一个视图,但相信我,它会让你的生活更轻松。你知道吗

提示:在模板中,您还可以使用权限限制用户看到的内容。您甚至可以在调用视图之前管理权限。你知道吗

{% if perms.app_label.can_do_something %}
<form here>
{% endif %}

The currently logged-in user's permissions are stored in the template variable {{ perms }}

参考文献:Check permission inside a template in Django

相关问题 更多 >