Search code examples
djangodjango-orm

Complex filtering with Q() Django


I have models Order and User:

class Order(Model):
    ...
    status = CharField(choices=STATUS, default=NEW, max_length=20)
    referral_user = ForeignKey("app.User", CASCADE, 'referal', blank=True, null=True)
    operator = ForeignKey("app.User", CASCADE,'operator', blank=True, null=True)

class User(Model):
    ...
    orders_for_all_operators = BooleanField(default=True)
    operators = ManyToManyField("User", related_name="admins")

I need to filter orders for operators like this:

  1. Status: New
  2. Operator: requested user or no operator.
  3. Order's referral_user: has the requested user in their operators field or orders_for_all_operators = True

I've tried this code but it's not working:

qs = queryset.filter(Q(Q(referral_user__in=self.request.user.admins.all()) | Q(user__orders_for_all_operators=True)) | Q(Q(operator=None) | Q(operator=self.request.user)))

Solution

  • Give this a try:

    from django.db.models import Q
    
    qs = Order.objects.filter(status='New').filter(
        Q(operator=self.request.user) | Q(operator=None),
        Q(referral_user__in=self.request.user.operators.all()) | Q(referral_user__orders_for_all_operators=True)
    )