问题
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