mbc
mbc

Reputation: 101

DjangoREST json parsing id instead of name

im new to Django (and to the DjangoREST framework)and and I've been struggling for a while with the following:

I want for "especies" (apologies for the portuguese..) to be a vector with the names of the model Especies(scroll down pls) and instead this is giving me the id corresponding to the Especie.

"especies": [
            13,
            14
        ]

I want, for example:

"especies": [
            Z1,
            Z2
        ]

Thanks in advance!

The JSON parsed:

    {
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
        "codigo": "Z3",
        "area": "Z_tres",
        "especies": [
            13,
            14
        ],
        "id": 17
    }
    ]
}

FROM THE DJANGO REST APP:

views.py

from django.shortcuts import render
from species.models import Especie, Zona, EspecieZona
from rest_framework import viewsets
from rest.serializers import ZonaSerializer

class ZonaViewSet(viewsets.ModelViewSet):
    queryset = Zona.objects.all()
    serializer_class = ZonaSerializer

serializers.py

from species.models import Zona
from rest_framework import serializers

class ZonaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Zona
        fields = ('codigo', 'area', 'especies', 'id')

The models.py on this app is empty.

FROM THE MAIN APP

models.py

from django.db import models

class Zona(models.Model):
    codigo          = models.CharField(max_length=120)
    area            = models.CharField(max_length=120)
    especies        = models.ManyToManyField("Especie", blank=True)
    def __str__(self):
        return self.codigo

class Especie(models.Model):
    nome            = models.CharField(max_length=120)
    nome_latino     = models.CharField(max_length=120)
    data_insercao   = models.DateTimeField(auto_now_add=True)
    actualizacao    = models.DateTimeField(auto_now=True)
    zonas           = models.ManyToManyField("Zona",blank=True )
    def __str__(self):
        return self.nome

I believe I have posted all the relevant code to this particular case.

Thanks again!

Upvotes: 2

Views: 68

Answers (1)

origamic
origamic

Reputation: 1116

models.py

class Zona(models.Model):
    codigo = models.CharField(max_length=120)
    area            = models.CharField(max_length=120)
    especies        = models.ManyToManyField("Especie", blank=True)

    def __str__(self):
        return self.codigo

    def get_especies(self):
        return self.especies.all().values_list('nome', flat=True)

serializers.py

class ZonaSerializer(serializers.ModelSerializer):
    especies = serializers.ReadOnlyField(source='get_especies')

Upvotes: 2

Related Questions