Search code examples
pythondjangodjango-querysetdjango-q

Django Queryset most accurate search result


I have to sort queryset by occurrence of elements from list in two fields. Currently I wrote part that find objects:

self.filter((reduce(operator.or_, ((Q(tags__contains=tag) | Q(name__contains=string)) for tag in string.split(' ')))))

but I can't find solution to get right ordering. Ordering by occurence of elements from list, in 'tags' field Would partly solve my issue. But I prefer not to iterate over all objects in queryset..


Solution

  • So, you want to make objects with certain tags to display in the top?

    There is similar problem. The idea is to add in select new field, which will hold boolean value, so you can sort by it.

    You should add this field using django extra queryset method.

    MyModel.objects.extra(
        select={
            'tags_occurance': "(tags LIKE '%tag1%') + (tags LIKE '%tag2%')"
        },
    ).order_by('-tags_occurance')
    

    Should be something like this.