poulpe/communication/models.py

65 lines
1.9 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-18 17:18:54 +02:00
unique_together = ("user", "content_type", "object_id")
2017-07-18 13:54:11 +02:00
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-18 17:18:54 +02:00
unique_together = ("group", "content_type", "object_id")
2017-07-18 13:54:11 +02:00
2017-07-15 18:37:47 +02:00
class SubscriptionMixin(models.Model):
2017-07-18 17:18:54 +02:00
user_subscriptions = GenericRelation(UserSubscription)
group_subscriptions = GenericRelation(GroupSubscription)
def get_all_subscribers(self):
2017-07-18 17:18:54 +02:00
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