Django中如何让登录用户仅查看分配给自己的Obiectiv模型?
解决Django中用户仅查看分配给自己的Obiectiv实例问题
你通过ManyToManyField将Obiectiv模型与User关联,目前登录用户能看到所有Obiectiv实例,需要调整视图查询逻辑,让用户仅查看分配给自己的实例。
你的模型代码(models.py)
class Obiectiv(models.Model): numeObiectiv = models.CharField(max_length=250) color = models.CharField(max_length=6, choices=COLOR_CHOICES, default='green') user = models.ManyToManyField(User)
原视图代码(views.py)
@login_required def home(request): obiective = Obiectiv.objects.all() return render(request, 'home.html', context={"obiective":obiective})
修改后的视图代码
只需要把查询所有实例改成过滤当前登录用户关联的实例,有两种可行写法:
写法一:通过反向关联查询
@login_required def home(request): obiective = request.user.obiectiv_set.all() return render(request, 'home.html', context={"obiective":obiective})
写法二:直接过滤Obiectiv模型
@login_required def home(request): obiective = Obiectiv.objects.filter(user=request.user) return render(request, 'home.html', context={"obiective":obiective})
模板说明
你的home.html代码不需要修改,模板仅负责循环展示obiective变量内容,修改视图后该变量已变为当前用户的专属实例集合。
内容的提问来源于stack exchange,提问作者Kertz
相关产品推荐
相关产品推荐

