poulpe/communication/models.py

57 lines
1.6 KiB
Python
Raw Normal View History

2017-07-15 18:13:45 +02:00
from django.db import models
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation
)
from django.contrib.contenttypes.models import ContentType
2017-07-15 21:22:15 +02:00
from django.utils.translation import ugettext_lazy as _
2017-07-15 18:13:45 +02:00
User = get_user_model()
2017-07-15 18:13:45 +02:00
class Subscription(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
2017-07-15 18:13:45 +02:00
2017-07-18 13:54:11 +02:00
class Meta:
abstract = True
2017-07-15 18:13:45 +02:00
class UserSubscription(Subscription):
2017-07-18 13:54:11 +02:00
user = models.ForeignKey(User)
is_unsub = models.BooleanField(
_("désinscription"),
default=False
2017-07-15 18:13:45 +02:00
)
2017-07-15 18:37:47 +02:00
2017-07-18 13:54:11 +02:00
class Meta:
verbose_name = _("souscription utilisateur")
2017-07-15 18:37:47 +02:00
class GroupSubscription(Subscription):
group = models.ForeignKey(Group)
2017-07-15 18:37:47 +02:00
2017-07-18 13:54:11 +02:00
class Meta:
verbose_name = _("souscription en groupe")
2017-07-15 18:37:47 +02:00
class SubscriptionMixin(models.Model):
subscribed_users = GenericRelation(UserSubscription)
subscribed_groups = GenericRelation(GroupSubscription)
2017-07-15 18:37:47 +02:00
2017-07-18 13:54:11 +02:00
def get_manual_subscribers(self):
return self.subscribed_users.filter(is_unsub=False)
2017-07-15 18:37:47 +02:00
2017-07-18 13:54:11 +02:00
def get_subscribers_from_groups(self):
return User.objects.filter(group__in=self.subscribed_groups.all())
def get_all_subscribers(self):
2017-07-18 13:54:11 +02:00
return (self.get_manual_subscribers()
.union(self.get_subscribers_from_groups())
.exclude(is_unsub=True))
class Meta:
abstract = True