How to get all the properties of objects using foreign key in django model

别说谁变了你拦得住时间么 提交于 2019-12-23 05:42:09

问题


Using Djangorestframework I had created rest api. I have two models in my app countries and states. I had related countries model to states model using Foreign key method, But while fetching list of states in States api i am getting states names, but in the place of country i am getting countries primary key id instead of it's name how can i get all the fields of Countries instead of 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

I had attached image u can see the country displaying primary id instead of it's name, how can i get name and all other related fields of countries..


回答1:


You can use depth serializer's option:

class statesSerializers(serializers.ModelSerializer):

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


来源:https://stackoverflow.com/questions/51233597/how-to-get-all-the-properties-of-objects-using-foreign-key-in-django-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!