Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django MySQL full text search

I need to implement full text search for my Django application, running MySQL as backend.

Let's say I've got a model as follows:

class MyItem(models.Model):     title = models.CharField()     short_description = models.TextField()     description = models.TextField() 

I would like to have results first for search term occurences in title, then in short_description and at the end in description field. I'll be happier if I don't have to use additional modules/applications for this task.

like image 768
edkirin Avatar asked Feb 12 '10 00:02

edkirin


2 Answers

The previously highest rated answer is deprecated. As of Django 1.10 there is no more search field lookup for MySQL databases (see the search section in the 1.10 documentation).

The release notes for 1.10 also propose a solution to this, by defining a custom lookup:

###__search query lookup

The search lookup, which supports MySQL only and is extremely limited in features, is deprecated. Replace it with a custom lookup:

from django.db import models  class Search(models.Lookup):    lookup_name = 'search'     def as_mysql(self, compiler, connection):        lhs, lhs_params = self.process_lhs(compiler, connection)        rhs, rhs_params = self.process_rhs(compiler, connection)        params = lhs_params + rhs_params        return 'MATCH (%s) AGAINST (%s IN BOOLEAN MODE)' % (lhs, rhs), params  models.CharField.register_lookup(Search) models.TextField.register_lookup(Search) 
like image 64
tbrlpld Avatar answered Oct 03 '22 23:10

tbrlpld


You can use full text search in django

MyItem.objects.filter(title__search="some search text") 

One thing is - you can't define a fulltext index from a Django model, you need to do in directly in a database (using PHPMyAdmin or SQL query)

See Django documentation for field lookup called search

like image 37
Silver Light Avatar answered Oct 04 '22 00:10

Silver Light