Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

python - Django, how to use filter to check if string field is contained in parameter

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()

which I found in the django docs

Question, how do I filter for the objects whose field values are contained in the querystring variable?

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()

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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)

Then loop and filter:

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

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

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...