[Profile] fix sorting podcasts
[mygpo.git] / mygpo / directory / models.py
blob270c0158eb88cacad920ca08dfef76a83c7b7902
1 from __future__ import unicode_literals
3 from django.core.cache import cache
5 from couchdbkit.ext.django.schema import *
7 from mygpo.podcasts.models import Podcast
8 from mygpo.utils import iterate_together
9 from mygpo.core.proxy import DocumentABCMeta
12 class Category(Document):
14 __metaclass__ = DocumentABCMeta
16 label = StringProperty(required=True)
17 updated = DateTimeProperty(required=True)
18 spellings = StringListProperty()
19 podcasts = ListProperty()
22 def merge_podcasts(self, podcasts):
23 """
24 Merges some entries into the current category.
25 """
27 key = lambda e: e.podcast
29 podcasts = sorted(podcasts, key=key)
30 self.podcasts = sorted(self.podcasts, key=key)
32 new_entries = []
34 for e1, e2 in iterate_together([self.podcasts, podcasts], key):
35 if e1 is None:
36 new_entries.append(e2)
38 elif e2 is None:
39 new_entries.append(e1)
41 else:
42 new_entries.append( max(e1, e2) )
44 self.podcasts = new_entries
47 # called from within a template where we can't pass parameters
48 def get_podcasts_more(self, start=0, end=40):
49 return self.get_podcasts(start, end)
52 def get_podcasts(self, start=0, end=10):
53 cache_id = 'category-%s-%d-%d' % (self._id, start, end)
55 podcasts = cache.get(cache_id)
56 if podcasts:
57 return podcasts
59 ids = self.podcasts[start:end]
61 # TODO: this should not be needed anymore after migration
62 if ids and not isinstance(ids[0], unicode):
63 return []
65 podcasts = Podcast.objects.filter(id__in=ids)
66 cache.set(cache_id, podcasts)
68 return podcasts
71 def get_weight(self):
72 return getattr(self, '_weight', len(self.podcasts))
75 def get_tags(self):
76 return self.spellings + [self.label]
78 def __repr__(self):
79 return '%s (+%d variants)' % (self.label, len(self.spellings))
82 class ExamplePodcasts(Document):
83 podcast_ids = StringListProperty()
84 updated = DateTimeProperty()