DjangoREST json解析id而不是name

时间:2017-11-16 16:34:24

标签: python json django django-models django-rest-framework

我刚接触Django(以及DjangoREST框架)并且我一直在努力与以下内容:

我希望“especies”(葡萄牙语道歉......)是一个带有Especies模型名称的向量(向下滚动),而是给我一个与Especie相对应的id。

"especies": [
            13,
            14
        ]

我想要,例如:

"especies": [
            Z1,
            Z2
        ]

提前致谢!

JSON已解析:

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

来自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')

此应用中的 models.py 为空。

来自主要应用

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

我相信我已将所有相关代码发布到此特定案例中。

再次感谢!

1 个答案:

答案 0 :(得分:1)

<强> 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')