Gidrek
Gidrek

Reputation: 750

Custom Dictionary in Django Rest Framework

I have tried to get a JSON like this:

{
        "course_name": "name",
        "course_id": "44",
        "icon": 1,
        "published_at":"2014-10-23T03:15:54Z",
        "skills": {
            "self":[
                {
                    "skill_name": "Cuidado Emocional",
                    "points": 5,
                },
                {
                    "skill_name": "Cuidado Físico",
                    "points": 5,
                }
            ],
            "abilities":[
                {
                    "skill_name": "Principios Básicos",
                    "points":5,
                },
                {
                    "skill_name": "Administración",
                    "points": 5,
                }
            ]

        },

Where the skills dictionary has a field that is type_hability, I want to group by the type_ability:

This is my model

class Ability(models.Model):
    ability = models.CharField("Habilidad", max_length=255)
    ability_type = models.CharField('Tipo', max_length=2, choices=ABILITY_TYPE)
    course = models.ForeignKey(Course, related_name='abilities')
    points = models.PositiveIntegerField()
    active = models.BooleanField("Activo", default=True)
    created_at = models.DateTimeField("Creado en", auto_now_add=True)
    updated_at = models.DateTimeField("Actualizado a las", auto_now=True)

    class Meta:
        verbose_name = u'Habilidad'
        verbose_name_plural = u"Habilidades"
        ordering = ["-created_at"]

    def __unicode__(self):
        return self.ability

I have tried to create a Serializer like this

class AbilitySerializer(serializers.ModelSerializer):
    dictAutoCuidado = {}
    dictHabilidades = {}

    class Meta:
        model = Ability
        fields = ('ability', 'points')

    def to_native(self, value):
        if value.ability_type == 'AU':
            self.dictAutoCuidado.update({
                'skill_name': value.ability,
                'points': value.points
            })
        else:
            self.dictHabilidades.update({
                'skill_name': value.ability,
                'points': value.points
            })

        return {
            'self': self.dictAutoCuidado,
            'ability': self.dictHabilidades
        }


class CourseListSerializer(serializers.ModelSerializer):
    author = serializers.RelatedField(source='author.name')
    objectives = serializers.RelatedField(many=True)
    abilities = AbilitySerializer(many=True)

    class Meta:
        model = Course
        fields = (
            'id',
            'title',
            'description',
            'objectives',
            'abilities',
        )

But when I reload my page, the JSON is

{
    "id": 1, 
    "title": "La vida es bella", 
    "created_at": "2014-10-23T02:06:21Z", 
    "abilities": [
        {
            "self": {
                "points": 100, 
                "skill_name": "Habilidad 1"
            }, 
            "ability": {
                "points": 250, 
                "skill_name": "Habilidad 2"
            }
        }, 
        {
            "self": {
                "points": 100, 
                "skill_name": "Habilidad 1"
            }, 
            "ability": {
                "points": 250, 
                "skill_name": "Habilidad 2"
            }
        }, 
        {
            "self": {
                "points": 100, 
                "skill_name": "Habilidad 1"
            }, 
            "ability": {
                "points": 250, 
                "skill_name": "Habilidad 2"
            }
        }
    ]
}

And the abilities are not group by as I want. Can you tell me what I am doing wrong and a way to fix this? I have tried with some queryset but is not working. I tried to override the init method but I did not find the way to return the custom dictonary group by as I want.

Thanks.

Upvotes: 0

Views: 1857

Answers (1)

jeevu94
jeevu94

Reputation: 718

i think these fields should be

dictAutoCuidado = serializers.DictField()
dictHabilidades = serializers.DictField()

link: https://www.django-rest-framework.org/api-guide/fields/#dictfield

Upvotes: 1

Related Questions