user2880391
user2880391

Reputation: 2791

Django complex query for OR

I'm using django 1.10

I've created this query which works for me:

filters_qs = filters_qs.filter(
    Q(
        user__in=[cache.user for cache in caches],
        status_id__in=[Status.Open['id'], Status.Empty['id']],
        revision=0
    ) |
    Q(
        user=None,
        status_id__in=[Status.Open['id'], Status.Empty['id']],
        revision=0
    )
)

I used the 'OR' because I'm looking for a result where the query set is either None or in the list. But - it looks not so 'pythonic'... it repeats the same code for minor change. Is there another way? for example, something like - (doesn't work)

Q(
  user__in=[cache.user for cache in caches] + [None],
  status_id__in=[
      Status.Open['id'],
      Status.Empty['id']
      ],
  revision=0
  )

Thanks.

Upvotes: 1

Views: 87

Answers (1)

SHIVAM JINDAL
SHIVAM JINDAL

Reputation: 2984

You should use isnull lookup for checking the None value. Try this:

filters_qs.filter(
    Q(user__in=map(lambda item: item.user, caches)) |
    Q(user__isnull=True),
    status_id__in=[
        Status.Open['id'],
        Status.Empty['id']
    ],
    revision=0
)

Upvotes: 4

Related Questions