问题

我有一个现有的** filter_kwargs用于“和”过滤,如何插入“或”查询?目前所谓的“OR”查询被视为“和”查询.

这是我的基本代码:

 search_text = form_data.get("search_text", "").strip(" ")

filter_kwargs = {
    "is_active": True,
    "is_admin": False,
}


if search_text != "":
    // these are the supposed "OR" queries. how do I insert "OR" queries in kwargs?
    filter_kwargs['user__first_name__icontains'] = search_text
    filter_kwargs['user__last_name__icontains'] = search_text
    filter_kwargs['user__email__icontains'] = search_text


Profiles = Profile.object.filter(**filter_kwargs)
 

  最佳答案

您可以将项目包装在Q对象中,并使用逻辑或者:

 from django.db.models import Q

Profiles = Profile.object.filter(Q(**filter_kwargs, _connector=Q.OR)) 

但是,看起来第一个项目应该被视为AND,您可以通过在过滤层添加它们(而不是Q -level)来做到这一点:

 filter_kwargs = {}
if search_text:
    filter_kwargs['user__first_name__icontains'] = search_text
    filter_kwargs['user__last_name__icontains'] = search_text
    filter_kwargs['user__email__icontains'] = search_text

Profiles = Profile.object.filter(
    Q(**filter_kwargs, _connector=Q.OR),
    is_active=True,
    is_admin=False
) 

  相同标签的其他问题

djangopython-3.xdjango-models
上一个问题: