program tip

Django에서 OR 쿼리 필터를 동적으로 작성하는 방법은 무엇입니까?

radiobox 2020. 9. 2. 15:28
반응형

Django에서 OR 쿼리 필터를 동적으로 작성하는 방법은 무엇입니까?


예에서 다중 OR 쿼리 필터를 볼 수 있습니다.

Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))

예를 들어, 결과는 다음과 같습니다.

[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]

그러나 목록에서이 쿼리 필터를 만들고 싶습니다. 그렇게하는 방법?

예 : [1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))


다음과 같이 쿼리를 연결할 수 있습니다.

values = [1,2,3]

# Turn list of values into list of Q objects
queries = [Q(pk=value) for value in values]

# Take one Q object from the list
query = queries.pop()

# Or the Q object with the ones remaining in the list
for item in queries:
    query |= item

# Query the model
Article.objects.filter(query)

더 복잡한 쿼리를 작성하려면 내장 된 Q () 객체의 상수 Q.OR 및 Q.AND를 다음과 같이 add () 메서드와 함께 사용하는 옵션도 있습니다.

list = [1, 2, 3]
# it gets a bit more complicated if we want to dynamically build
# OR queries with dynamic/unknown db field keys, let's say with a list
# of db fields that can change like the following
# list_with_strings = ['dbfield1', 'dbfield2', 'dbfield3']

# init our q objects variable to use .add() on it
q_objects = Q()

# loop trough the list and create an OR condition for each item
for item in list:
    q_objects.add(Q(pk=item), Q.OR)
    # for our list_with_strings we can do the following
    # q_objects.add(Q(**{item: 1}), Q.OR)

queryset = Article.objects.filter(q_objects)

# sometimes the following is helpful for debugging (returns the SQL statement)
# print queryset.query

Python의 reduce 기능을 사용하여 Dave Webb의 답변을 작성하는 더 짧은 방법 :

# For Python 3 only
from functools import reduce

values = [1,2,3]

# Turn list of values into one big Q objects  
query = reduce(lambda q,value: q|Q(pk=value), values, Q())  

# Query the model  
Article.objects.filter(query)  

from functools import reduce
from operator import or_
from django.db.models import Q

values = [1, 2, 3]
query = reduce(or_, (Q(pk=x) for x in values))

SQL IN 문을 사용하는 것이 더 낫습니다.

Article.objects.filter(id__in=[1, 2, 3])

참조 의 검색어 API를 참조 .

동적 논리를 사용하여 쿼리를 작성해야하는 경우 다음과 같이 할 수 있습니다 (추악 + 테스트되지 않음).

query = Q(field=1)
for cond in (2, 3):
    query = query | Q(field=cond)
Article.objects.filter(query)

문서 참조 :

>>> Blog.objects.in_bulk([1])
{1: <Blog: Beatles Blog>}
>>> Blog.objects.in_bulk([1, 2])
{1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}
>>> Blog.objects.in_bulk([])
{}

Note that this method only works for primary key lookups, but that seems to be what you're trying to do.

So what you want is:

Article.objects.in_bulk([1, 2, 3])

In case we want to programmatically set what db field we want to query:

import operator
questions = [('question__contains', 'test'), ('question__gt', 23 )]
q_list = [Q(x) for x in questions]
Poll.objects.filter(reduce(operator.or_, q_list))

Using solution with reduce and or_ operator here how can you filter by multiply fields.

from functools import reduce
from operator import or_
from django.db.models import Q

filters = {'field1': [1, 2], 'field2': ['value', 'other_value']}

qs = Article.objects.filter(
   reduce(or_, (Q(**{f'{k}__in': v}) for k, v in filters.items()))
)

p.s. f is a new format strings literal aded in python3.6


You can use the |= operator to programmatically update a query using Q objects.


This one is for dynamic pk list:

pk_list = qs.values_list('pk', flat=True)  # i.e [] or [1, 2, 3]

if len(pk_list) == 0:
    Article.objects.none()

else:
    q = None
    for pk in pk_list:
        if q is None:
            q = Q(pk=pk)
        else:
            q = q | Q(pk=pk)

    Article.objects.filter(q)

Another option I wasn't aware of until recently - QuerySet also overrides the &, |, ~, etc, operators. The other answers that OR Q objects are a better solution to this question, but for the sake of interest/argument, you can do:

id_list = [1, 2, 3]
q = Article.objects.filter(pk=id_list[0])
for i in id_list[1:]:
    q |= Article.objects.filter(pk=i)

str(q.query) will return one query with all the filters in the WHERE clause.


easy..
from django.db.models import Q import you model args = (Q(visibility=1)|(Q(visibility=0)&Q(user=self.user))) #Tuple parameters={} #dic order = 'create_at' limit = 10

Models.objects.filter(*args,**parameters).order_by(order)[:limit]

참고URL : https://stackoverflow.com/questions/852414/how-to-dynamically-compose-an-or-query-filter-in-django

반응형