django rest 框架 POST 请求因嵌套序列化而失败
Posted
技术标签:
【中文标题】django rest 框架 POST 请求因嵌套序列化而失败【英文标题】:django rest framework POST request fails with nested serialization 【发布时间】:2016-05-31 04:56:44 【问题描述】:我对 url http://127.0.0.1:8000/airlines/ 的 POST 请求失败
这是我项目中的模型和相应的序列化程序。最初我想创建航空公司信息,然后再添加航班
谁能告诉我哪里出错了
models.py
class AirlineFirm(models.Model):
operator_name = models.CharField(max_length=30)
def __unicode__(self):
return "%s" % (self.operator_name)
class Flight(models.Model):
flight_num = models.CharField(max_length=7, primary_key=True)
src = models.CharField(max_length=20)
dest = models.CharField(max_length=20)
outbound_time = models.DateTimeField()
inbound_time = models.DateTimeField()
num_of_seats = models.IntegerField()
ticketPrice = models.FloatField()
delayed = models.BooleanField()
airlinefirm = models.ForeignKey(AirlineFirm)
serializers.py
class FlightSerializer(serializers.Serializer):
flight_num = serializers.CharField(read_only=True)
src = serializers.CharField()
dest = serializers.CharField()
outbound_time = serializers.DateTimeField()
inbound_time = serializers.DateTimeField()
num_of_seats = serializers.IntegerField()
ticketPrice = serializers.FloatField()
delayed = serializers.BooleanField()
airlinefirm = serializers.RelatedField(read_only='True')
#passengers = models.ManyToManyField(Passenger)
def create(self, validated_data):
return Flight.objects.create(**validated_data)
def update(self, instance, validated_data):
pass
class AirlineSerializer(serializers.ModelSerializer):
flights = FlightSerializer(many=True)
class Meta:
model = AirlineFirm
fields = ('operator_name','flights')
def create(self, validated_data):
flights_data = validated_data.pop('flights')
airlinefirm = AirlineFirm.objects.create(**validated_data)
for flight_data in flights_data:
Flight.objects.create(airlinefirm=airlinefirm, **flight_data)
return airlinefirm
views.py
@api_view(['GET','POST'])
def airline(request, format=None):
if request.method == 'GET':
airlines = AirlineFirm.objects.all()
serializer = AirlineSerializer(airlines, many=True)
return Response(serializer.data)
if request.method == 'POST':
#data = JSONParser().parse(request)
serializer = AirlineSerializer(data=request.data)
#import pdb;pdb.set_trace()
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
import pdb;pdb.set_trace()
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
当我向我的航空公司视图类发送 POST 请求 http://127.0.0.1:8000/airlines/ 时,我收到 404 响应
http 请求
import json
import requests
payload = 'operator_name':'AmericanAirlines','flights':[]
headers = 'Content-type':'application/json'
r = requests.post('http://127.0.0.1:8000/',data=json.dumps(payload),headers=headers)
这是错误信息:
AttributeError:尝试在序列化程序 AirlineSerializer
上获取字段 flights
的值时出现 AttributeError。
序列化程序字段可能命名不正确,并且与 AirlineFirm
实例上的任何属性或键都不匹配。
原始异常文本为:“AirlineFirm”对象没有“航班”属性。
[2016 年 2 月 18 日 13:43:58] "POST /airlines/ HTTP/1.1" 500 112039
【问题讨论】:
【参考方案1】:如果你的 urls.py 中的 api 不存在,你需要和一个端点,然后在你的请求中指向它,比如:
r = requests.post('http://127.0.0.1:8000/airlines',data=json.dumps(payload),headers=headers)
【讨论】:
我确实提到了端点 url(r'^airlines/$',views.airline), 酷,是的,我不确定它是否真的在你的网址中,所以我说如果不是就添加它。无论哪种方式,您是否看到我在回答中添加到 requests.post 的请求中缺少什么? 我做了更多搜索,发现Flight model airportfirm = models.ForeignKey(AirlineFirm, related_name="flights")中没有提到related_name以上是关于django rest 框架 POST 请求因嵌套序列化而失败的主要内容,如果未能解决你的问题,请参考以下文章
从 Vuejs 到 Django REST 框架的 Axios POST 请求
如何使用带有 ajax 的 DJANGO REST 框架发出 POST 请求
Django REST框架:POST请求:仅在数据不存在时如何保存数据
Django REST framework框架之GET, POST, PUT, PATCH, DELETE等API请求接口设计