56 lines
1.6 KiB
Python
56 lines
1.6 KiB
Python
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
|
|
from django.utils.translation import ugettext_lazy as _
|
|
|
|
User = get_user_model()
|
|
|
|
|
|
class Subscription(models.Model):
|
|
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
|
|
object_id = models.PositiveIntegerField()
|
|
content_object = GenericForeignKey('content_type', 'object_id')
|
|
|
|
class Meta:
|
|
abstract = True
|
|
|
|
|
|
class UserSubscription(Subscription):
|
|
user = models.ForeignKey(User)
|
|
is_unsub = models.BooleanField(
|
|
_("désinscription"),
|
|
default=False
|
|
)
|
|
|
|
class Meta:
|
|
verbose_name = _("souscription utilisateur")
|
|
|
|
|
|
class GroupSubscription(Subscription):
|
|
group = models.ForeignKey(Group)
|
|
|
|
class Meta:
|
|
verbose_name = _("souscription en groupe")
|
|
|
|
|
|
class SubscriptionMixin(models.Model):
|
|
subscribed_users = GenericRelation(UserSubscription)
|
|
subscribed_groups = GenericRelation(GroupSubscription)
|
|
|
|
def get_manual_subscribers(self):
|
|
return self.subscribed_users.filter(is_unsub=False)
|
|
|
|
def get_subscribers_from_groups(self):
|
|
return User.objects.filter(group__in=self.subscribed_groups.all())
|
|
|
|
def get_all_subscribers(self):
|
|
return (self.get_manual_subscribers()
|
|
.union(self.get_subscribers_from_groups())
|
|
.exclude(is_unsub=True))
|
|
|
|
class Meta:
|
|
abstract = True
|