from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import gettext_lazy as _ class Assignment(models.Model): user = models.ForeignKey("auth.User", on_delete=models.PROTECT) subject_ct = models.ForeignKey(ContentType, on_delete=models.PROTECT) subject_id = models.PositiveIntegerField() subject = GenericForeignKey('subject_ct', 'subject_id') class Meta: unique_together = [ ("subject_ct", "subject_id"), ] @classmethod def assign(cls, user, subject): Assignment.objects.get_or_create( user=user, subject_ct=ContentType.objects.get_for_model(subject), subject_id=subject.pk, ) @classmethod def delete(cls, subject_id): Assignment.objects.filter( subject_id=subject_id, ).delete() class NoteQuerySet(models.QuerySet): def for_user(self, user): notes = ( self.filter(author=user) ) if user.has_perm('users.view_all_notes'): notes |= ( self.exclude(author=user).annotate(owner_label=models.F('author__username')) ) elif user.groups.filter(name=settings.SUPER_LEXICOGRAPHS_GROUP_NAME).exists(): notes |= ( self.exclude(author=user) .filter(super=True) ) # notes |= ( # self.exclude(author=user).filter(author__groups__name=settings.SUPER_LEXICOGRAPHS_GROUP_NAME) # .annotate(owner_label=models.Value(_('Super'), output_field=models.CharField())) # ) return notes class Note(models.Model): author = models.ForeignKey("auth.User", on_delete=models.PROTECT) subject_ct = models.ForeignKey(ContentType, on_delete=models.PROTECT) subject_id = models.PositiveIntegerField() subject = GenericForeignKey('subject_ct', 'subject_id') title = models.CharField(max_length=100) note = models.TextField() created_at = models.DateTimeField(auto_now_add=True) type = models.CharField(max_length=100, default=None, blank=True, null=True) super = models.BooleanField(default=False) objects = models.Manager.from_queryset(NoteQuerySet)()