Search code examples
djangodjango-querysetdjango-q

Filter by user is not staff using Q in another model queryset


I have the following model:

class APC(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='apc', on_delete=models.SET_NULL)
  type= models.CharField(choices=TYPE_CHOICES, max_length=5, blank=True, null=True)

I want to get APC objects that have one of two specific types, and user is not staff.

I'm starting with:

apcs = APC.objects.filter(
        ~Q(user is staff),
        Q(type=TYPE_CHOICES_A) | Q(type=TYPE_CHOICES_B)
)

Solution

  • Try to do it without Q:

    apcs = APC.objects.filter(user__is_staff=False, type__in=(TYPE_CHOICES_A, TYPE_CHOICES_B))