From: Stefan Koegl Date: Fri, 17 Sep 2010 09:03:52 +0000 (+0300) Subject: simplify generation of SearchEntrys X-Git-Url: https://repo.or.cz/w/mygpo.git/commitdiff_plain/6b09e7427b520f2ef00eadffd8439f58ca2310ae simplify generation of SearchEntrys --- diff --git a/mygpo/data/models.py b/mygpo/data/models.py index 7b2ab96b..b52f65f8 100755 --- a/mygpo/data/models.py +++ b/mygpo/data/models.py @@ -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') diff --git a/mygpo/search/util.py b/mygpo/search/util.py index cd774760..deba497d 100644 --- a/mygpo/search/util.py +++ b/mygpo/search/util.py @@ -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] +