我正在尝试使用Django REST框架在数据库中创建一个新条目,并且能够成功发送请求,但是validated_data
为空:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from rest_framework import viewsets
from django.shortcuts import get_object_or_404, get_list_or_404
from .models import GetPurchases, CarFax
from .serializers import PurchasesSerializer
from .serializers import CarFaxSerializer
from rest_framework.response import Response
# Create your views here.
class GetCarFax(viewsets.ModelViewSet):
''' This view will be used for POSTing new carfax reports to the database '''
queryset = CarFax.objects.all()
serializer_class = CarFaxSerializer
# authentication_classes = []
permission_classes = []
#print('TEST')
def list(self, request):
# accessed at url: ^api/v1/carfax/$
queryset = CarFax.objects.all()
serializer = CarFaxSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None, *args, **kwargs):
# accessed at url: ^api/v1/retrieve/{pk}/$
queryset = CarFax.objects.all()
record = get_list_or_404(queryset, vin__exact=pk)
serializer = CarFaxSerializer(record, many=True)
return Response(serializer.data)
def create(self, request, **validated_data):
print('TEST')
print(request.data)
print(validated_data)
serializer = CarFaxSerializer(CarFax.objects.create(**validated_data))
headers = self.get_success_headers(serializer.data)
print(serializer.data)
print(headers)
return Response(serializer.data, headers=headers)
serializers.py
class CarFaxSerializer(serializers.ModelSerializer):
class Meta:
model = CarFax
fields = ('vin', 'structural_damage', 'total_loss',
'accident', 'airbags', 'odometer', 'recalls',
'last_updated')
打印request.data
时,我可以看到发送的数据。但是validated_data
是空的,这是我用来创建模型的字典。
答案 0 :(得分:1)
首先,您的 GetCarFax
类看起来很凌乱:(因为您将覆盖大多数方法,但不会提供任何方法视图的优势。因此,将您的 GetCarFax
视图类更改为以下类别,
class GetCarFax(viewsets.ModelViewSet):
"""
This view will be used for POSTing new carfax reports to the database
"""
queryset = CarFax.objects.all()
serializer_class = CarFaxSerializer
# authentication_classes = []
permission_classes = []
lookup_field = 'myfieldname'
这几行代码将为您处理所有 CRUD 操作:)
答案 1 :(得分:1)
接受的答案是一个很好的重构,但它没有回答问题,因此可能对未来的读者(比如我自己,刚刚经历过这个问题)没有帮助。验证数据为空的真正原因是,当您在 .create
上覆盖 ModelViewSet
时,您会清除序列化器模型字段绑定,并且必须像在常规序列化器上一样显式指定它们。
CarFax 序列化程序应该像这样定义:
class CarFaxSerializer(serializers.ModelSerializer):
vin = serializers.CharField(23),
structural_damage = serializers.BooleanField(),
total_loss = serializers.BooleanField(),
accident = serializers.BooleanField(),
airbags = serializers.BooleanField(),
odometer = serializers.IntegerField(),
recalls = serialziers.BooleanField(),
last_updated = serializers.DateField(),
class Meta:
model = CarFax
fields = ('vin', 'structural_damage', 'total_loss',
'accident', 'airbags', 'odometer', 'recalls',
'last_updated')