首页 > 解决方案 > 有没有办法与 q 对象连接?

问题描述

我一直在努力实现这一点。我正在尝试构建一个动态查询集,其中条件将基于用户输入。用户可以决定按名字或姓氏或两者的组合进行搜索。如果仅按姓氏搜索,则不会将名字查询添加到查询集中。我目前正在使用它来搜索所有输入的字段。

results = documents.objects.filter(
    Q(f_filer__filer_first_name__istartswith=request.GET.get('first_name', 
'')) & (f_filer__filer_last_name__istartswith=request.GET.get('last_name', 
'')) & 
Q(f_office__o_office_name__istartswith=request.GET.get('office_name', ''))
    & Q(f_doc_year__exact=request.GET.get('report_year', ''))
    & Q(f_report_id__exact=request.GET.get('filing_type', ''))       
    ).values('f_filer__filer_first_name',
          'f_filer__filer_last_name',
          'f_office__o_office_name',
          'f_date_received',
          'f_start_travel_date',
          'f_end_travel_date',
          'f_doc_year',
          'f_report__r_title')

标签: django-modelsdjango-viewsdjango-ormqobject

解决方案


您可以使用连接Q对象|,它充当“或”:

first_name = request.GET.get('first_name', '')
last_name = request.GET.get('last_name', '')
Q(
    f_filer__filer_first_name__istartswith=first_name,
    f_filer__filer_last_name__istartswith=last_name
) |
Q(f_filer__filer_first_name__istartswith=first_name) |
Q(f_filer__filer_last_name__istartswith=last_name)

如果您的应用程序搜索量很大,则可能值得考虑设置适当的搜索后端。

你使用 Postgres 吗?如果是这样,使用 Django 的 Postgres全文搜索可能会简化事情并有助于使代码更易于维护。

如果您不使用 Postgres,使用django-haystack设置搜索后端会给您带来类似的好处,并允许用户使用AutoQuery构建类似 Google 的查询。例如,-用于排除一个术语和一个精确短语的引号。


推荐阅读