Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Filter Django database for field containing any value in an array

I have a django model and a field representing a users full name. My client wants me to set up a filter to search for a user based on an array of strings where all of them have to be case insensitive contained within the full name.

For example

If a users full_name = "Keith, Thomson S."

And I have a list ['keith','s','thomson']

I want to perform the filter equivalent of

Profile.objects.filter(full_name__icontains='keith',full_name__icontains='s',full_name__icontains='thomson')

The problem is this list can be of dynamic size - so I do not know how to do this.

Anyone have any ideas?

question from:https://stackoverflow.com/questions/8949145/filter-django-database-for-field-containing-any-value-in-an-array

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

1 Answer

0 votes
by (71.8m points)

Make successive calls to filter, like so:

queryset = Profile.objects.all()
strings = ['keith', 's', 'thompson']
for string in strings:
    queryset = queryset.filter(full_name__icontains=string)

Alternatively you can & together a bunch of Q objects:

condition = Q(full_name__icontains=s[0])
for string in strings[1:]:
    condition &= Q(full_name__icontains=string)
queryset = Profile.objects.filter(condition) 

A more cryptic way of writing this, avoiding the explicit loop:

import operator
# ...
condition = reduce(operator.and_, [Q(full_name__icontains=s) for s in strings])
queryset = Profile.objects.filter(condition)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...