taggedItem.py 1.02 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 5 6 7 8
from backend_app.models.abstract.basic_module import (
    BasicModule,
    BasicModuleSerializer,
    BasicModuleViewSet,
)
Florent Chehab's avatar
Florent Chehab committed
9 10
from backend_app.models.tag import Tag
from backend_app.validators.tag import tagged_item_validation
Florent Chehab's avatar
Florent Chehab committed
11 12


13
class TaggedItem(BasicModule):
Florent Chehab's avatar
Florent Chehab committed
14 15 16 17
    """
    Abstract model to represent a tagged item
    """

18
    tag = models.ForeignKey(Tag, related_name="+", on_delete=models.PROTECT)
Florent Chehab's avatar
Florent Chehab committed
19
    custom_content = JSONField(default=dict)
Florent Chehab's avatar
Florent Chehab committed
20 21 22 23 24

    class Meta:
        abstract = True


25
class TaggedItemSerializer(BasicModuleSerializer):
Florent Chehab's avatar
Florent Chehab committed
26 27 28 29
    """
    Serializer for tagged items
    """

30 31 32
    def validate(self, attrs):
        attrs = super().validate(attrs)

33 34
        tagged_item_validation(attrs)
        return attrs
Florent Chehab's avatar
Florent Chehab committed
35 36


37
class TaggedItemViewSet(BasicModuleViewSet):
Florent Chehab's avatar
Florent Chehab committed
38 39 40 41
    """
    Tagged item viewset
    """

42
    def get_queryset(self):
Florent Chehab's avatar
Florent Chehab committed
43 44 45
        """
        Extend the queryset for a bit of optimization
        """
46
        return super().get_queryset().prefetch_related("tag")