使用 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
您可以使用depth
序列化程序的选项:
class statesSerializers(serializers.ModelSerializer):
class Meta:
model = states
fields = '__all__'
depth = 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句