基于用户组的过滤视图



我试图进一步过滤查询,以仅显示组与登录用户组匹配的记录。我是Python的新手,不知道如何在下面的视图中添加一个额外的过滤器。

视图

@login_required(login_url='login')
def home(request):
q= request.GET.get('q') if request.GET.get('q') != None else '' 
infs= Infringement.objects.filter(Q(name__icontains=q) |
Q(infringer__name__icontains=q)
          
)

模型
class Infringement (models.Model):
name = models.CharField(max_length=200)
link = models.CharField(null=True, blank=True, max_length=200)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
infringer = models.ForeignKey(Infringer, on_delete=models.SET_NULL,null=True)
player = models.ForeignKey(Player, on_delete=models.SET_NULL,null=True)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL,null=True)
status = models.ForeignKey(Status, on_delete=models.SET_NULL,null=True)
groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1)

class Meta:
ordering = ['-updated', '-created']`

我试着添加下面的内容,但它不起作用。

infs= Infringement.objects.filter(Q(name__icontains=q) |
Q(infringer__name__icontains=q|) 
(groups=request.user.groups)                                         
)

您可以使用:

from django.db.models import Q

@login_required(login_url='login')
def home(request):
q = request.GET.get('q', '')
infs = Infringement.objects.filter(
Q(name__icontains=q) | Q(infringer__name__icontains=q),
groups__user=request.user,
)
# …

相关内容

  • 没有找到相关文章

最新更新