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:
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)))
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)
)