Django,如何使用过滤器检查参数中是否包含字符串字段 [英] Django, how to use filter to check if string field is contained in parameter

查看:937
本文介绍了Django,如何使用过滤器检查参数中是否包含字符串字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个带有文本字段的模型:

Say, I have a model with a text field:

class SomeModel
    keyword=models.CharField(null=True, max_length=255)

现在,我知道如何检查参数字符串(让调用变量查询字符串包含在字段关键字中:

Now, I know how to check if a parameter string (lets call the variable "querystring" is contained in the field keyword:

results = SomeModel.objects.filter(keyword_icontains=querystring).all()

我在 django文档

问题,如何处理

很抱歉,如果我的问题令人困惑...也许示例可以阐明...
在Django文档中,如果我的关键字字段包含例如 python-django,那么对于包含 django的查询字符串,我可以使用

Apologies if my question is confusing... maybe an example will clarify... In django docs, if my keyword field contains,for example, 'python-django', then, for a querystring that contains 'django', I can extract the object that contains that field with an

results=SomeModel.objects.filter(keyword_icontains=querystring).all()
or results=SomeModel.objets.filter(keyword_icontains='django').all()

但是,我想提取关键字字段包含在查询字符串中的所有行/对象吗?例如,如果querystring包含在Django中,如何创建过滤器?那么我希望结果包含其关键字字段具有值'django','filter'等的所有对象...

But say, I want to extract all rows/objects whose keyword field is contained in a querystring? For example, if querystring contains 'In django, how do I create a filter'? then I want results to contain all objects whose keyword fields have the values 'django', 'filter', etc...

推荐答案

您必须将输入拆分成单词(取决于您对单词的定义),然后对其进行迭代,将各种结果查询集(大多数可能为空)串联起来。

You'll have to split your input into words (depending on your definition of "word"), and then iterate over them, concatenating the various resulting querysets (most of which are likely to be empty).

要进行拆分,可以使用正则表达式,捕获所有字母和撇号(但是,如果有人将其用作输入而不是标准ASCII撇号,则会错过智能引号):

To split, you could use a regex, catching all letters and the apostrophe (but you'll miss a smart-quote, if someone uses that as input instead of the standard ASCII apostrophe):

words = re.split(r"[^A-Za-z']+", querystring)

然后循环并过滤:

query = Q()  # empty Q object
for word in words:
    # 'or' the queries together
    query |= Q(keyword_icontains=word)
results = SomeModel.objects.filter(query).all()

上面的代码未经测试,我想到了或查询和一个e mpty Q()来自此答案

The above code is untested, and I got the idea to 'or' the queries and an empty Q() from this answer.

取决于您的下一步(s),在每个循环步骤中直接评估查询,并附加到 results 列表中,可能对您更好(例如使用 itertools.chain ,根据这个答案)。

Depending on your next step(s), evaluating the query directly in each loop step, appending to a results list, might work better for you (using e.g. itertools.chain, as per this answer).

这篇关于Django,如何使用过滤器检查参数中是否包含字符串字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆