1

I want to perform OR query using django ORM. I referred this answer and it fits my need.

I have a list of integers which gets generated dynamically. These integers represent user id in a particular table. This table also has a date field. I want to query the database for all user ids in the list for a given date.

For example: From below table, I want records for user ids 2 and 3 for the date 2015-02-28

id |    date
---------------
 1 | 2015-02-23
 1 | 2015-02-25
 1 | 2015-02-28
 2 | 2015-02-28
 2 | 2015-03-01
 3 | 2015-02-28

I am unable to figure out which of the following two should be perfect for my use case:

Table.objects.filter(reduce(lambda x, y: (x | y) & Q(date=datetime.date(2015, 2, 28)), [Q(user_id=i) for i in ids])

OR

Table.objects.filter(reduce(lambda x, y: (x | y), [Q(user_id=i) for i in ids]) & Q(date=datetime.date(2015, 2, 28))

Both of the above yield similar output at the moment. Without lambda, below query would fit my need:

Table.objects.filter(Q(user_id=3) & Q(date=datetime.date(2015, 2, 28))| Q(user_id=2) & Q(date=datetime.date(2015, 2, 28)))
Community
  • 1
  • 1
Dharmit
  • 5,498
  • 2
  • 27
  • 30

1 Answers1

5

I think you do not need reduce and Q objects here, you can just do:

Table.objects.filter(
    user_id__in=[2,3],
    date=datetime.date(2015, 2, 28),
)
Todor
  • 15,307
  • 5
  • 55
  • 62