Merge branch 'jupyter'
[mygpo.git] / mygpo / podcastlists / models.py
blob2a0ef37d05276466c501f2763b78591b0468b9e2
1 from django.db import models
2 from django.urls import reverse
3 from django.conf import settings
4 from django.contrib.contenttypes.models import ContentType
5 from django.contrib.contenttypes.fields import GenericForeignKey
7 from mygpo.core.models import UpdateInfoModel, OrderedModel, UUIDModel
8 from mygpo.podcasts.models import Podcast
9 from mygpo.votes.models import VoteMixin
10 from mygpo.utils import set_ordered_entries
13 class PodcastList(UUIDModel, VoteMixin, UpdateInfoModel):
14 """ A user-curated collection of podcasts """
16 # the user that created (and owns) the list
17 user = models.ForeignKey(settings.AUTH_USER_MODEL,
18 on_delete=models.CASCADE)
20 # the user-assigned title of the list
21 title = models.CharField(max_length=512)
23 # the slug (unique for the user) that is derived from the title
24 slug = models.SlugField(max_length=128)
26 class Meta:
27 unique_together = [
28 # a slug is unique for a user
29 ('user', 'slug'),
32 @property
33 def max_order(self):
34 return max([-1] + [e.order for e in self.entries.all()])
36 @property
37 def num_entries(self):
38 return self.entries.count()
40 def add_entry(self, obj):
41 entry, created = PodcastListEntry.objects.get_or_create(
42 podcastlist=self,
43 content_type=ContentType.objects.get_for_model(obj),
44 object_id=obj.id,
45 defaults={
46 'order': self.max_order + 1,
50 def set_entries(self, podcasts):
51 """ Updates the list to include the given podcast, removes others """
53 existing = {e.content_object: e for e in self.entries.all()}
54 set_ordered_entries(self, podcasts, existing, PodcastListEntry,
55 'content_object', 'podcastlist')
58 class PodcastListEntry(UpdateInfoModel, OrderedModel):
59 """ An entry in a Podcast List """
61 # the list that the entry belongs to
62 podcastlist = models.ForeignKey(PodcastList,
63 related_name='entries',
64 on_delete=models.CASCADE,
67 # the object (Podcast or PodcastGroup) that is in the list
68 content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
69 object_id = models.UUIDField()
70 content_object = GenericForeignKey('content_type', 'object_id')
72 class Meta(OrderedModel.Meta):
73 unique_together = [
74 ('podcastlist', 'order'),
75 ('podcastlist', 'content_type', 'object_id'),