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