serializers.py
2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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')