Created
June 25, 2011 21:57
-
-
Save fadur/1046946 to your computer and use it in GitHub Desktop.
Subclassing django's QuerySet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from django.db import models, connection | |
| class SearchQuerySet(models.query.QuerySet): | |
| """SearchQuerySet""" | |
| def __init__(self, model=None, fields=None, using=None, query=None): | |
| super(SearchQuerySet, self).__init__(model, query, using) | |
| self._search_fields = fields | |
| def search(self, squery): | |
| """creates a sql match expresion like | |
| SELECT field_name, MATCH(`product`.`name`, `product`.`description`) | |
| AGAINST ('nike') AS 'relevance' FROM `product` WHERE | |
| MATCH(`product`.`name`, `product`.`description`) AGAINST ('nike') | |
| """ | |
| meta = self.model._meta | |
| columns = [meta.get_field(name) for name in self._search_fields] | |
| table_culumn_names = ["%s.%s" % (connection.ops.quote_name(meta.db_table), connection.ops.quote_name(field.column)) for field in columns] | |
| full_column_names = ", ".join(table_culumn_names) | |
| expr = ("MATCH(%s) AGAINST ('%s')" % (full_column_names, squery)) | |
| return self.extra(select={'relevance': expr}, where=[expr]) | |
| class SearchManager(models.Manager): | |
| """SearchManager""" | |
| use_for_related_fields = True | |
| def __init__(self, fields): | |
| super(SearchManager, self).__init__() | |
| self._search_fields = fields | |
| def get_query_set(self): | |
| """overrides get_query_set method and loads the custom SearchQuerySet""" | |
| return SearchQuerySet(self.model, self._search_fields) | |
| def search(self, squery): | |
| """the custom search method applied to the model""" | |
| return self.get_query_set().search(squery) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment