問題

我有一個現有的** 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
上一個問題: