我在django项目中使用django-role-permission,并通过装饰器控制对视图的访问,如下所示:
@canAccessDashboard
def index(request):
""" Merchant settings main page"""
try:
return render(request, 'dashboard/merchantsettings.html')
except Exception as e:
return HttpResponse('NOK', status=500)
装饰者`canAccessDashboard如下:
def canAccessDashboard(func):
def func_wrapper(*args):
user = cache.get('UserObj_' + str(args[0].user.id))
if user is None:
user = User.objects.get(id=args[0].user.id)
cache.set('UserObj_' + str(args[0].user.id), user, 300)
if has_permission(user, "access_dasboard"):
if not has_permission(user, "add_merchant_address"):
return render(args[0], 'dashboard/specify_address.html')
return func(*args)
return redirect(settings.VERIFY_REGISTRATION_URL)
return func_wrapper
问题在于每当使用装饰器时我都会得到8个重复的查询,下面是来自django-debug-toolbar的查询摘录:
SELECT•••FROM“auth_permission”INNER JOIN “auth_user_user_permissions”ON(“auth_permission”。“id”= “auth_user_user_permissions”。“permission_id”)INNER JOIN “django_content_type”ON(“auth_permission”。“content_type_id”= “django_content_type”。“id”)在哪里 “auth_user_user_permissions”。“user_id”= 16 ORDER BY “django_content_type”。“app_label”ASC,“django_content_type”。“模型” ASC,“auth_permission”。“代号”ASC
重复8次。SELECT•••FROM“auth_permission”WHERE (“auth_permission”。“content_type_id”= 4 AND “auth_permission”。“codename”='add_merchant_address')
重复8次SELECT•••FROM“auth_permission”WHERE (“auth_permission”。“content_type_id”= 4 AND “auth_permission”。“codename”='immediate_cashout')
重复8次。SELECT•••FROM“auth_permission”WHERE (“auth_permission”。“content_type_id”= 4 AND “auth_permission”。“codename”='access_dasboard') 重复8次
似乎正在查询available_permissions
available_permissions = {
'access_dasboard': False,
'add_merchant_address': False,
'immediate_cashout': False,
'update_merchant_address': False
}
使用django-role-permissions
是一个问题吗?如何减少重复查询?
谢谢。