9
9
95506682020-08-21 13:47:34
Django
9550668, 2020-08-21 13:47:34

QS filter does not work. What is the reason?

Good day to all.

There are 2 code options, 1 works and the second doesn't. The search parameter embedded in the variable is somehow incorrectly passed. Can you suggest how to fix it?
Working:
qs = qs.filter(Q(type=2) | Q(type=1))
Not working:

query = "Q(type=2) | Q(type=1)"
qs = qs.filter(query)

Throws an error:
ValueError: too many values ​​to unpack (expected 2)

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-08-21
@9550668

from functools import reduce
from operator import or_

from django.db.models import Q

values = (Q(type=int(j)) for j in (i.strip() for i in (query_type or '').split(',')) if j.isdigit())
query = reduce(or_, values, Q())

qs = qs.filter(query)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question