Simple search in Django

后端 未结 4 1098
北海茫月
北海茫月 2021-01-30 17:36

I have a really simple blog application and I want to add a really simple search feature to it.

There are 3 key fields to my model.

class BlogPost(models         


        
4条回答
  •  不思量自难忘°
    2021-01-30 18:07

    From the Django source:

    # Apply keyword searches.
    def construct_search(field_name):
        if field_name.startswith('^'):
            return "%s__istartswith" % field_name[1:]
        elif field_name.startswith('='):
            return "%s__iexact" % field_name[1:]
        elif field_name.startswith('@'):
            return "%s__search" % field_name[1:]
        else:
            return "%s__icontains" % field_name
    
    if self.search_fields and self.query:
        for bit in self.query.split():
            or_queries = [models.Q(**{construct_search(str(field_name)): bit}) for field_name in self.search_fields]
            qs = qs.filter(reduce(operator.or_, or_queries))
        for field_name in self.search_fields:
            if '__' in field_name:
                qs = qs.distinct()
                break
    

    Clearly, it uses the database options to perform search. If nothing else, you should be able to reuse some of the code from it.

    So says the documentation too: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields

    The full text search, however, uses the MySQL index (only if you are using MySQL).

提交回复
热议问题