serializers.py 2.26 KB
from actstream.models import Action
from rest_framework import serializers

from usuario.serializers import UsuarioSerializer
# from persona.serializers import (
#     DomicilioSerializer,
#     FotoComplementariaPersonaSerializer,
#     IdentificacionCromaticaSerializer,
#     PersonaSerializer,
#     VinculoFamiliarSerializer,
#     HuellaDactilarSerializer,
#     VinculoFamiliarSinIdentificarSerializer,
#     IdentificacionDecadactilarSerializer, AutorizacionMenorSerializer,
# )
from usuario.models import Usuario


class ActivityGenericRelatedField(serializers.Field):
    """
    DRF Serializer field that serializers GenericForeignKey fields on the :class:`~activity.models.Action`
    of known model types to their respective ActionSerializer implementation.
    """

    def to_representation(self, value):
        from edicto.serializers import EdictoSerializer, PrecioSerializer

        MAPEO_SERIALIZADORES_POR_MODELO = {
            "Usuario": UsuarioSerializer,
            "Edicto": EdictoSerializer,
            "Precio": PrecioSerializer
        }

        nombre_modelo = type(value).__name__
        serializer_cls = MAPEO_SERIALIZADORES_POR_MODELO.get(nombre_modelo, None)

        if serializer_cls:
            # se genera un nuevo diccionario donde se le suma otro diccionario conteniendo el elemento "type"
            data = {**{'type': nombre_modelo}, **{'id': value.id}, **serializer_cls(value, context=self.context).data}
        else:
            data = str(value)

        return data


class ActorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Usuario
        fields = (
            'username',
            'first_name',
            'last_name',
            'cuil'
        )


class ActionSerializer(serializers.Serializer):
    """
    DRF serializer for :class:`~activity.models.Action`.
    """
    actor = ActorSerializer(read_only=True)
    verb = serializers.CharField(read_only=True)
    action_object = ActivityGenericRelatedField(read_only=True)
    target = ActivityGenericRelatedField(read_only=True)
    timestamp = serializers.DateTimeField(read_only=True)
    data = serializers.DictField(read_only=True)

    class Meta:
        model = Action
        fields = ('id', 'actor', 'verb', 'action_object', 'target', 'timestamp', 'data')