Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search multiple fields of django model without 3rd party app

I have a single model in my django app that I want to create a search form for. Is there a way to search all the fields in the model at once with the same search string? I've looked into xapian and solr but they seem like a lot of overhead for searching over 1 model. I want to be able to say something like:

results = Assignment.objects.filter(any_column = search_string)

I realize there might not be something that concise but right now the only option I can come up with other than using a search app is to check each field separately and concatenate the results together.

like image 539
Matt Phillips Avatar asked Nov 26 '25 07:11

Matt Phillips


1 Answers

Once you have all the field names you can create Q objects using kwarg expansion and use reduce() along with operator.or_ to turn them into a single query.

qgroup = reduce(operator.or_, (Q(**{fieldname: value}) for fieldname in fieldnames))
asgns = Assignment.objects.filter(qgroup)
like image 175
Ignacio Vazquez-Abrams Avatar answered Nov 27 '25 21:11

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!