taggedItem.py 1.34 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1
from django.db import models
Florent Chehab's avatar
Florent Chehab committed
2 3

from backend_app.fields import JSONField
4
from backend_app.models.abstract.module import Module, ModuleSerializer, ModuleViewSet
Florent Chehab's avatar
Florent Chehab committed
5
from backend_app.models.tag import Tag
6 7 8 9 10 11 12
from backend_app.validation.validators import TaggedItemValidator

VALIDATOR = TaggedItemValidator()


def validate_tagged_item(tag_name, content):
    VALIDATOR(tag_name, content)
Florent Chehab's avatar
Florent Chehab committed
13 14


15
class TaggedItem(Module):
Florent Chehab's avatar
Florent Chehab committed
16 17 18 19
    """
    Abstract model to represent a tagged item
    """

20
    tag = models.ForeignKey(Tag, related_name="+", on_delete=models.PROTECT)
21 22 23 24 25 26 27 28
    content = JSONField(default=dict)

    def save(self, *args, **kwargs):
        """
        Custom save function to ensure consistency of the content with the tag.
        """
        validate_tagged_item(self.tag.name, self.content)
        return super().save(*args, **kwargs)
Florent Chehab's avatar
Florent Chehab committed
29 30 31 32 33

    class Meta:
        abstract = True


34
class TaggedItemSerializer(ModuleSerializer):
Florent Chehab's avatar
Florent Chehab committed
35 36 37 38
    """
    Serializer for tagged items
    """

39 40
    def validate(self, attrs):
        attrs = super().validate(attrs)
41
        validate_tagged_item(attrs["tag"].name, attrs["content"])
42
        return attrs
Florent Chehab's avatar
Florent Chehab committed
43 44


45
class TaggedItemViewSet(ModuleViewSet):
Florent Chehab's avatar
Florent Chehab committed
46 47 48 49
    """
    Tagged item viewset
    """

50
    def get_queryset(self):
Florent Chehab's avatar
Florent Chehab committed
51 52 53
        """
        Extend the queryset for a bit of optimization
        """
54
        return super().get_queryset().prefetch_related("tag")