superSearch is intended to make it easier to make complex OR queries, thusly hitting the database less.
EXAMPLE: Searching for a user named 'Eric Neuman' would be difficult because first_name and last_name are separate fields. However, with superSearch, it's a breeze.
query = ['Eric Neuman']
f = ['first_name','last_name']
s = query.split(' ')
m = ['icontains']
results = superSearch(User, f, m,s)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from django.db.models.query import Q
def superSearch(model, fields, matches, strings):
"""
Designed to lessen the code needed to run complex searches with ORed filters.
Model: the model being queried.
fields: an iterable containing string names of fields to query.
match: an iterable containing strings of what type of Django lookup to apply to those fields.
strings: an iterable containing strings to be matched.
"""
queries = []
for field in fields:
for string in strings:
for match in matches:
kwargs = {'%s__%s' % (field, match): string}
queries.append(Q(**kwargs))
q = Q()
for query in queries:
q = q | query
return model.objects.filter(q)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
This is nice! Maybe you could remove the last loop, something like this:
#
Please login first before commenting.