Django如何检查对象是否在多个字段中包含字符串 [英] Django how to check if objects contains string in multiple fields
问题描述
因此,我有一个名为Puzzle的模型,其中包含标题,问题和主题.我希望能够通过输入字符串来搜索难题.我的搜索栏还包含三个复选框:- 标题- 问题-主题
So I have a model called Puzzle which contains a title, question, and a subject. I want to be able to search for puzzles by entering a string. My search bar also contains three checkboxes: - title - question - subject
我希望能够以某种方式查询我的数据库,以查看所打勾的字段是否包含搜索文本.例如,如果标题和问题被打勾,我将查询拼图的标题是否包含此字符串,或者其问题包含该字符串.有什么方法可以在Django中查询吗?
I want to somehow be able to query my database to see if the ticked fields contain the search text. For example, if title and question were ticked, I would query to see if the puzzle's title contains this string OR its questions contains the string. Is there any way to query this in Django?
我知道,如果我只想检查这些字段之一(例如标题),我可以这样做:
I know that if I wanted to check just one of these fields, for instance the title, I could just do this:
Puzzle.objects.filter(title__contains=search_text)
但是我希望能够动态查询被打勾的字段.
But I want to be able to dynamically query the fields that are ticked.
当前,我的视图包含三个布尔值:标题,问题和主题.布尔值被选中时为True,否则为false.
Currently, my view contains three boolean values: title, question, and subject. The boolean is True is it is ticked, and false if it is not ticked.
我如何处理这三个布尔值以及Django查询,以便能够动态查询我的数据库?
How can I manipulate these three booleans along with Django queries to be able to dynamically query my database?
谢谢
推荐答案
You can do OR
queries using Q
objects:
from django.db.models import Q
Puzzle.objects.filter(
Q(title__contains=search_text) |
Q(question__contains=search_text) |
Q(subject__contains=search_text)
)
当然,您可以动态地构建此 Q
对象:
Of course you can build this Q
object dynamically:
q = Q()
if title:
q |= Q(title__contains=search_text)
if question:
q |= Q(question__contains=search_text)
if subject:
q |= Q(subject__contains=search_text)
# If you want no result if none of the fields is selected
if q:
queryset = Puzzle.objects.filter(q)
else:
queryset = Puzzle.objects.none()
# Or if you want all results if none of the fields is selected
queryset = Puzzle.objects.filter(q)
如果列表中有所有选定字段(即 search_fields = ['title','subject']
,您甚至可以使其更通用:
If you have all selected fields in a list (ie. search_fields = ['title', 'subject']
, you can even make it more generic:
from functools import reduce
from operators import or_
q = reduce(or_, [Q(**{f'{f}__contains': search_text}) for f in search_fields], Q())
Puzzle.objects.filter(q)
这篇关于Django如何检查对象是否在多个字段中包含字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!