django-models - 有没有办法与 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')
解决方案
您可以使用连接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 的查询。例如,-
用于排除一个术语和一个精确短语的引号。
推荐阅读
- c++11 - 我们如何在集合的地图中添加一个元素...例如.map
>mp; 在 C++14 中 - python - 当我尝试将我的 Django 项目部署到 Heroku 时,它没有检测到 buildpack。有人可以帮我吗?
- javascript - 如何提取2 个标签之间的内容并将该内容放在单独的数组中
- python - Python循环中的内存错误
- php - 递归不会继续下一项
- javascript - 如何使用 ID 或 Class 在一个 amp HTML 文档的不同位置调用一个 Javascript 函数?
- python - 为什么在 Django 中运行 PostgreSQL UPDATE 时出现错误“不是在字符串格式化期间转换的所有参数”?
- python - 创建 float 的子类,以防所有算术运算都返回同一类的对象(不是 float)
- javascript - 在 React 中将子表单的数据传递给父(应用程序)
- javascript - 我必须在哪里使用等待?