我正在制作一个CRUD应用程序,我在视图中有一段代码:
def dashboard(request):
template = 'dashboard/index.html'
form = CustomerForm()
if request.user.groups.filter(name__in=['West']).exists():
customers = Customer.objects.filter(Q(department='630') | Q(department='635')).all()
elif request.user.groups.filter(name__in=['North']).exists():
customers = Customer.objects.filter(Q(department='610') | Q(department='615') | Q(department='620')).all()
elif request.user.groups.filter(name__in=['East']).exists():
customers = Customer.objects.filter(Q(department='660') | Q(department='655') | Q(department='650')).all()
elif request.user.groups.filter(name__in=['South']).exists():
customers = Customer.objects.filter(Q(department='640') | Q(department='645')).all()
elif request.user.groups.filter(name__in=['North-West']).exists():
customers = Customer.objects.filter(Q(department='625')).all()
else:
customers = Customer.objects.all()
context = {
"customers": customers,
"form": form,
}
return render(request, template, context)
我有单独的创建,更新和删除功能,也需要使用相同的if语句。我了解了模型管理并创建了以下内容:
class CustomerQueryset(models.query.QuerySet):
def customer_department_query(self):
if request.user.groups.filter(name__in=['West']).exists():
customers = Customer.objects.filter(Q(department='630') | Q(department='635')).all()
elif request.user.groups.filter(name__in=['North']).exists():
customers = Customer.objects.filter(Q(department='610') | Q(department='615') | Q(department='620')).all()
elif request.user.groups.filter(name__in=['East']).exists():
customers = Customer.objects.filter(Q(department='660') | Q(department='655') | Q(department='650')).all()
elif request.user.groups.filter(name__in=['South']).exists():
customers = Customer.objects.filter(Q(department='640') | Q(department='645')).all()
elif request.user.groups.filter(name__in=['North-West']).exists():
customers = Customer.objects.filter(Q(department='625')).all()
else:
customers = Customer.objects.all()
class CustomerManager(models.Manager):
def get_queryset(self):
return CustomerQueryset(self.model, using=self.db)
def get_customer_group(self):
return self.get_queryset().customer_department_query()
然后我发现模型管理员无法访问请求,因此我创建了以下中间件:
class GetUser(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
user = (request.user)
request.current_user = user
user_group = request.user.groups.all()
print(user)
print(user_group)
response = self.get_response(request)
return response
当我刷新我的应用程序时,shell会打印用户名和用户组,但如何在Queryset / Model Manager中访问此信息?我是在正确的道路上还是有更好的方法来做到这一点?
非常感谢任何帮助。
答案 0 :(得分:3)
这整个方法都是错误的。
有一个原因是你无法从管理员那里访问“当前用户”,这就是在很多情况下没有当前用户 - 如果代码是从shell或离线任务执行的,如果用户未登录,依此类推。
更好的方法是将此方法设置为User模型本身 - 如果您还没有自定义用户模型,则可以使用此添加的方法定义简单代理模型,并将AUTH_USER_MODEL设置为指向该类。然后,该方法可以直接访问self.groups
。
注意,使用__in
而不是单独的Q对象可以使您的代码更简单,并且最后不需要.all()
:
customers = Customer.objects.filter(department__in=['630', '635'])