1

this code works well

from django.db.models import Q
filtered = Article.objects.filter(Q(authers__id=2) | Q(issues__id=1) | Q(issues__id=3) )

However now I have list like this below, and want to make filter dynamically.

ids = [1,2,3]
for id in ids:
    eachQ = Q(authers__id=isId)
#then......

how can I make query ???

2 Answers 2

1

Querying same field for different values(or condition) you can use __in key.

 possibilities = [1,2,3]
 Article.objects.filter(field__in=posibilities)

Also for dynamic queries you can pass **kwargs to filter method:

query_key = 'your_field_name__in'
Article.objects.filter(**{query_key:[1,2,3]#your search value})

You can add your multiple model field into kwargs param:

query = {'field_1':value_1,'field_2':value_2,'field_3__contains':value_3}#for example
Article.objects.filter(**query)
Sign up to request clarification or add additional context in comments.

1 Comment

I can use the first way, it helps me very simply!!! and thanks for alternative ways.
1

If you have a list of values for just one field, it`s better to use 'in' filter:

ids = [1,2,3]
articles = Article.objects.filter(authers__id__in=ids)

Otherwise, for creating 'OR' filter iteratively:

from django.db.models import Q

filters = Q()
ids = [1, 2, 3]

for pk in ids:
    filters |= Q(authers__id=pk)

articles = Article.objects.filter(filters)

This can be used for dynamic filtering by multiple model fields and values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.