fix typos, missing imports
[mygpo.git] / mygpo / search / models.py
blob150a6530dccdd34d0fb9a4eeb25f23c2d592a7cc
1 from django.db import models
2 from mygpo.search.util import tag_string
3 from mygpo.data.models import PodcastTag
4 from mygpo.api.models import Podcast, PodcastGroup
5 import shlex
8 class SearchEntryManager(models.Manager):
10 def search(self, q):
11 qs = SearchEntry.objects.all()
12 try:
13 tokens = shlex.split(q)
14 except ValueError:
15 tokens = [q]
17 for query in tokens:
18 qs = qs.filter(text__icontains=query)
20 return qs.order_by('-priority')
23 class SearchEntry(models.Model):
24 text = models.TextField(db_index=True)
25 obj_type = models.CharField(max_length=20, db_index=True)
26 obj_id = models.IntegerField(db_index=True)
27 tags = models.CharField(max_length=200, db_index=True)
28 priority = models.IntegerField(db_index=True)
30 objects = SearchEntryManager()
32 @classmethod
33 def from_object(cls, obj=None, subscriber_count=None):
34 """
35 Create a new SearchEntry from either a Podcast or a PodcastGroup
36 """
37 entry = SearchEntry()
38 entry.text = obj.title
39 entry.obj_id = obj.id
40 entry.priority = subscriber_count or obj.subscriber_count()
42 if isinstance(obj, Podcast):
43 entry.obj_type = 'podcast'
44 podcasts = [obj]
45 elif isinstance(obj, PodcastGroup):
46 entry.obj_type = 'podcast_group'
47 podcasts = Podcast.objects.filter(group=group)
49 entry.tags = tag_string(PodcastTag.objects.filter(podcast__in=podcasts))
50 return entry
53 def __repr__(self):
54 return "<%s '%s'>" % (self.__class__.__name__, self.text[:20])
57 def get_object(self):
58 if self.obj_type == 'podcast':
59 return Podcast.objects.get(id=self.obj_id)
60 elif self.obj_type == 'podcast_group':
61 return PodcastGroup.objects.get(id=self.obj_id)
62 else:
63 return None
65 def get_podcast(self):
66 """
67 Returns a podcast which is representative for this search-result
68 If the entry is a non-grouped podcast, it is returned
69 If the entry is a podcast group, one of its podcasts is returned
70 """
71 obj = self.get_object()
73 if isinstance(obj, Podcast):
74 return obj
75 elif isinstance(obj, PodcastGroup):
76 return obj.podcasts()[0]
77 else:
78 return None