What is the cause for the degradation of environment?
Capitalism, corruption, consuming society? - OVERPOPULATION!
Please, save the Planet - kill yourself...

Tuesday, October 16, 2018

Chaining AND operators in Django

Sometimes in Dango you need to compose query with several  `Q(query) & Q(other_query) &...` and the number of such queries changes dynamically. Here is a quick example how to solve it:

import operator

ids = [1, 2, 3]
queries = [Q(some_m2m_relation__pk=pk) for pk in id]
result = SomeModel.objects.filter(
    reduce(operator.and_, queries)
)

No comments :

Post a Comment