-->

Search in Django and GET with multiple words

2019-09-11 14:54发布

问题:

Could you tell me what should I use or where to look if I want to make something like this: When someone types "aaa bbb" (?t=aaa+bbb) in search field, it would only find those models, in which Title field is "aaa bbb", but not "aaa ccc bbb". How to change for example this code to make it find all titles, in which Titles is "aaa" or "bbb" word?

if 't' in request.GET:
    search = request.GET['t']

result = somemodel.objects.filter(Title__icontains = search).order_by('-pub_date')

Or in Title are "aaa" and "bbb" words, but not exatcly one after another? Should I change "icontains" to something else? Or make some loop to split "aaa bbb" into "aaa" and "bbb" if yes - how?)

回答1:

Like this, but split on whitespace (.split()) and use the appropriate field in the Q objects.