simplify generation of SearchEntrys
authorStefan Koegl <stefan@skoegl.net>
Fri, 17 Sep 2010 09:03:52 +0000 (17 12:03 +0300)
committerStefan Koegl <stefan@skoegl.net>
Fri, 17 Sep 2010 09:03:52 +0000 (17 12:03 +0300)
mygpo/data/models.py
mygpo/search/util.py

index 7b2ab96..b52f65f 100755 (executable)
@@ -4,6 +4,30 @@ from mygpo.api.models import Podcast, Episode, Device, ToplistEntry, PodcastGrou
 from mygpo import settings
 
 
+class PodcastTagManager(models.Manager):
+
+    def top_tags_for_podcast(self, podcast):
+        """
+        returns the most-assigned tags for the given podcast
+        """
+        tags = PodcastTag.objects.filter(podcast=podcast)
+        return self.top_tags(tags)
+
+    def top_tags(self, tags=None):
+        """
+        returns the most-assigned tags
+
+        If param tags is given, it is expected to be a PodcastTag-QuerySet.
+        The method is then restricted to this QuerySet, otherwise all tags
+        are considered
+        """
+        if not tags:
+            tags = PodcastTag.objects.all()
+        tags = tags.values('tag').annotate(count=Count('id'))
+        tags = sorted(tags, key=lambda x: x['count'], reverse=True)
+        return tags
+
+
 class PodcastTag(models.Model):
     tag = models.CharField(max_length=100)
     podcast = models.ForeignKey(Podcast)
@@ -11,6 +35,8 @@ class PodcastTag(models.Model):
     user = models.ForeignKey(User, null=True)
     weight = models.IntegerField(default=1)
 
+    objects = PodcastTagManager()
+
     class Meta:
         db_table = 'podcast_tags'
         unique_together = ('podcast', 'source', 'user', 'tag')
index cd77476..deba497 100644 (file)
@@ -15,9 +15,7 @@ def podcast_group_entry(group, subscriber_count=None):
     entry.obj_id = group.id
 
     podcasts = Podcast.objects.filter(group=group)
-    tags = PodcastTag.objects.filter(podcast__in=podcasts).annotate(count=Count('podcast')).order_by('count')
-    tag_string = ','.join([t.tag for t in tags])[:200]
-    entry.tags = tag_string
+    entry.tags = tag_string(PodcastTag.objects.filter(podcast__in=podcasts))
 
     entry.priority = subscriber_count
 
@@ -35,11 +33,19 @@ def podcast_entry(podcast, subscriber_count=None):
     entry.obj_type = 'podcast'
     entry.obj_id = podcast.id
 
-    tags = PodcastTag.objects.filter(podcast=podcast).annotate(count=Count('podcast')).order_by('count')
-    tag_string = ','.join([t.tag for t in tags])[:200]
-    entry.tags = tag_string
+    entry.tags = tag_string(PodcastTag.objects.filter(podcast=podcast))
 
     entry.priority = subscriber_count
 
     return entry
 
+
+def tag_string(tags, max_length=200):
+    """
+    returns a string of the most-assigned tags
+
+    tags is expected to be a PodcastTag QuerySet
+    """
+    tags = PodcastTag.objects.top_tags(tags)
+    return ','.join([t['tag'] for t in tags])[:max_length]
+