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") unique_together = ("user", "content_type", "object_id") class GroupSubscription(Subscription): group = models.ForeignKey(Group) class Meta: verbose_name = _("souscription en groupe") unique_together = ("group", "content_type", "object_id") class SubscriptionMixin(models.Model): user_subscriptions = GenericRelation(UserSubscription) group_subscriptions = GenericRelation(GroupSubscription) def get_all_subscribers(self): subscribed_users = User.objects.filter( usersubscription__in=self.user_subscriptions.filter(is_unsub=False) ) subscribed_groups = Group.objects.filter( groupsubscription__in=self.group_subscriptions.all() ) subscribers_from_groups = User.objects.filter( groups__in=subscribed_groups, ).exclude( usersubscription__in=self.user_subscriptions.filter( is_unsub=True ) ) return subscribed_users.union(subscribers_from_groups) class Meta: abstract = True