]> git.0d.be Git - django-panik-combo.git/blobdiff - panikombo/models.py
add episode auto selection cell
[django-panik-combo.git] / panikombo / models.py
index 0f74a5b3a2132f9959b6cdc4e9963f80d5ccb388..0c63576a74ea833dee46f3b9164ade3266c49e44 100644 (file)
@@ -2,9 +2,13 @@ from django import template
 from django.db import models
 from django.utils.translation import ugettext_lazy as _
 
+from taggit.managers import TaggableManager
+
 from combo.data.models import CellBase
 from combo.data.library import register_cell_class
 
+from emissions.models import Episode
+
 @register_cell_class
 class SoundCell(CellBase):
     soundfile = models.ForeignKey('emissions.SoundFile', null=True)
@@ -59,3 +63,39 @@ class EpisodeCell(CellBase):
                         self.episode.emission.title,
                         self.episode.title)
         return ''
+
+
+@register_cell_class
+class EpisodeAutoSelectionCell(CellBase):
+    title = models.CharField(_('Title'), max_length=50, blank=True)
+    tags = TaggableManager(_('Tags'), blank=True)
+    category = models.ForeignKey('emissions.Category', null=True, blank=True)
+
+    class Meta:
+        verbose_name = _('Automatic Episode Selection')
+
+    def render(self, context):
+        tmpl = template.loader.get_template('panikombo/episode_auto_selection.html')
+        context['title'] = self.title
+
+        episodes_queryset = Episode.objects.select_related()
+        if self.category:
+            episodes_queryset = episodes_queryset.filter(emission__categories__in=[self.category.id])
+        if self.tags:
+            episodes_queryset = episodes_queryset.filter(tags__in=self.tags.all())
+
+        episodes_queryset = episodes_queryset.extra(select={
+                        'first_diffusion': 'emissions_diffusion.datetime',
+                        },
+                        select_params=(False, True),
+                        where=['''datetime = (SELECT MIN(datetime)
+                                                FROM emissions_diffusion
+                                               WHERE episode_id = emissions_episode.id)'''],
+                        tables=['emissions_diffusion'],
+                    ).order_by('-first_diffusion').distinct()
+        context['episodes'] = episodes_queryset
+        return tmpl.render(context)
+
+    def get_default_form_class(self):
+        from .forms import EpisodeAutoSelectionCellForm
+        return EpisodeAutoSelectionCellForm