Use Django's new UUIDField
[mygpo.git] / mygpo / podcastlists / models.py
blobea1038591e9fd69ca6bfd08a600a18da3b27e1ca
1 from django.db import models
2 from django.core.urlresolvers import reverse
3 from django.conf import settings
4 from django.contrib.contenttypes.models import ContentType
5 from django.contrib.contenttypes import generic
7 from mygpo.core.models import UpdateInfoModel, OrderedModel, UUIDModel
8 from mygpo.podcasts.models import Podcast
9 from mygpo.flattr import FlattrThing
10 from mygpo.votes.models import VoteMixin
11 from mygpo.utils import set_ordered_entries
14 class PodcastList(UUIDModel, VoteMixin, UpdateInfoModel):
15 """ A user-curated collection of podcasts """
17 # the user that created (and owns) the list
18 user = models.ForeignKey(settings.AUTH_USER_MODEL,
19 on_delete=models.CASCADE)
21 # the user-assigned title of the list
22 title = models.CharField(max_length=512)
24 # the slug (unique for the user) that is derived from the title
25 slug = models.SlugField(max_length=128)
27 class Meta:
28 unique_together = [
29 # a slug is unique for a user
30 ('user', 'slug'),
33 @property
34 def max_order(self):
35 return max([-1] + [e.order for e in self.entries.all()])
37 @property
38 def num_entries(self):
39 return self.entries.count()
41 def add_entry(self, obj):
42 entry, created = PodcastListEntry.objects.get_or_create(
43 podcastlist=self,
44 content_type=ContentType.objects.get_for_model(obj),
45 object_id=obj.id,
46 defaults={
47 'order': self.max_order + 1,
51 def get_flattr_thing(self, domain, username):
52 """ Returns a "Thing" which can be flattred by other Flattr users """
53 return FlattrThing(
54 url = reverse('list-show', args=[username, self.slug]),
55 title = self.title,
56 description = u'A collection of podcasts about "%s" by %s user %s' % (self.title, domain, username),
57 category = u'audio',
58 hidden = None,
59 tags = None,
60 language = None,
63 def set_entries(self, podcasts):
64 """ Updates the list to include the given podcast, removes others """
66 existing = {e.content_object: e for e in self.entries.all()}
67 set_ordered_entries(self, podcasts, existing, PodcastListEntry,
68 'content_object', 'podcastlist')
71 class PodcastListEntry(UpdateInfoModel, OrderedModel):
72 """ An entry in a Podcast List """
74 # the list that the entry belongs to
75 podcastlist = models.ForeignKey(PodcastList,
76 related_name='entries',
77 on_delete=models.CASCADE,
80 # the object (Podcast or PodcastGroup) that is in the list
81 content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT)
82 object_id = models.UUIDField()
83 content_object = generic.GenericForeignKey('content_type', 'object_id')
85 class Meta(OrderedModel.Meta):
86 unique_together = [
87 ('podcastlist', 'order'),
88 ('podcastlist', 'content_type', 'object_id'),