在models.py中,我有以下模型:
class Project(models.Model):
project_name = models.CharField(max_length=255, unique=True, blank=False)
def __str__(self):
return str(self.project_name)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
role = models.CharField(choices=ROLE_CHOICES, max_length=255, default='Agent')
town = models.CharField(max_length=100)
project = models.ManyToManyField(Project)
def __str__(self):
return str('Advanced user informations')
class News(models.Model):
title = models.CharField(max_length=255, blank=False)
content = HTMLField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
在我的views.py中,我有:
def news(request):
news_list = News.objects.all().order_by('-id')
paginator = Paginator(news_list, 5)
page = request.GET.get('page')
news = paginator.get_page(page)
return render(request, 'news.html', {'news': news})
现在我想实现用户只能看到他参与的项目的新闻。
类似的东西:
News.objects.filter(News with a project that the User is linked to)
但我不确定什么是解决这个问题的有效方法。也许有人有小费?
答案 0 :(得分:0)
这应该这样做:
News.objects.filter(project__profile_set__user=request.user)
答案 1 :(得分:0)
这个怎么样,
News.objects.filter(project__in=request.user.profile.project.all())