I am trying to filter the query further to only show records where the Groups matches the logged in users group. I am new to Python and not sure how to add an additional filter into the below view.
View
@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)
)
Model
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']`
I tried adding the below but it doesn't work.
infs= Infringement.objects.filter(Q(name__icontains=q) |
Q(infringer__name__icontains=q|)
(groups=request.user.groups)
)
CodePudding user response:
You can filter with:
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,
)
# …