Created
February 18, 2012 03:01
-
-
Save kyleterry/1857109 to your computer and use it in GitHub Desktop.
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
class SearchableBaseModel(BaseModel): | |
""" | |
Subclasses of this are required to implement: | |
searchable_fields | |
A list of fields to do general search on, used for | |
ordering results as well. | |
""" | |
_aggregate_searchable_field = models.TextField(blank=True, null=True, editable=False, db_index=True) | |
searchable_fields = [] | |
class Meta: | |
abstract = True | |
@classmethod | |
def search(cls, query): | |
if not query or len(query.strip()) == 0: | |
return cls.objects.all() | |
else: | |
queries = query.strip().split(" ") | |
return cls.objects.filter(reduce(lambda t, q: t & Q(_aggregate_searchable_field__icontains=q), queries, Q())) | |
def _calclate_aggregate_searchable_field(self): | |
try: | |
s = self.__unicode__() | |
except: | |
s = '' | |
for attr_string in self.searchable_fields: | |
try: | |
s += ';' + eval('self.%s' % (attr_string)) | |
except: | |
pass | |
return s | |
def save(self, *args, **kwargs): | |
if self.id is None: | |
self._aggregate_searchable_field = '' | |
super(SearchableBaseModel, self).save(*args, **kwargs) | |
if 'force_insert' in kwargs: | |
del kwargs['force_insert'] | |
self._aggregate_searchable_field = self._calclate_aggregate_searchable_field() | |
super(SearchableBaseModel, self).save(*args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment