如何在Django模型中使用外键获取对象的所有属性

时间:2018-07-08 15:41:13

标签: django django-rest-framework django-serializer

使用Djangorestframework创建了rest api。我在应用程式的国家和地区有两种模式。我使用外键方法将相关国家模型转换为国家模型,但是在获取国家api中的国家列表时,我正在获取国家名称,但是在国家的地方,我正在获取国家主键ID而不是其名称我该如何获取全部国家字段而不是PK ID

----------
Models.py code
class countries(models.Model):
    country = models.CharField(max_length=10)


    def __str__(self):
        return  self.country


class states(models.Model):
    state = models.CharField(max_length=15)
    country = models.ForeignKey(countries, on_delete=models.PROTECT)

    def __str__(self):
        return self.state

    ----------
    Serializers.py code

    from rest_framework import  serializers
    from .models import countries, states

    class countiresSerializers(serializers.ModelSerializer):

        class Meta:
            model = countries
            fields = '__all__'

    class statesSerializers(serializers.ModelSerializer):

        class Meta:
            model = states
            fields = '__all__'

    ----------
    Viewset.py code--
    from django.shortcuts import render

    from django.http import HttpResponse
    from django.shortcuts import get_object_or_404
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework import status
    from.models import countries, states
    from .serializers import countiresSerializers, statesSerializers


    class countryList(APIView):


        def get(self, request):
            country1 = countries.objects.all()
            serializer = countiresSerializers(country1, many=True)
            return Response (serializer.data)


        def __pos__(self):
            pass


    class statesList(APIView):

        def get(self, request):
            state = states.objects.all()
            serializer = statesSerializers(state, many=True)
            return Response (serializer.data)

        def __pos__(self):
            pass

我已附上图片,可以看到显示主要ID而不是名称的国家/地区,如何获取名称以及国家/地区的所有其他相关字段。.enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用depth序列化器的选项:

class statesSerializers(serializers.ModelSerializer):

    class Meta:
        model = states
        fields = '__all__'
        depth = 1