我有一个像这样的serializerclass:
class EmployeeSerializer(serializers.ModelSerializer):
bio = BioSerializer()
# designation = GroupListSerializer()
# department = GroupListSerializer()
class Meta:
model = Employee
fields = ['user','bio','tax_id_number','account_number','joining_date','designation','department']
如何正确地在django中为此创建POST
方法:
到目前为止,这就是我所拥有的:
class EmployeeCreateView(generics.CreateAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
def post(self, request, format=None):
designation = Group.objects.get(id=request.data['designation'],)
department = Group.objects.get(id=request.data['department'],)
user =User.objects.get(id=request.data['user'],)
bio =Bio.objects.get(id=request.data['bio'],)
# user=User.objects.get(id=request.data['user'],)
employee = Employee.objects.create(
tax_id_number=request.data['tax_id_number'],
account_number=request.data['account_number'],
joining_date=request.data['joining_date'],
designation =designation,
department =department,
user=user,
bio=bio,
)
return Response(status=status.HTTP_201_CREATE
d)
但是当我发布帖子请求时,我会在日志中收到以下内容:
MultiValueDictKeyError at /hr/employee_create/
"'bio'"
答案 0 :(得分:2)
我认为您不需要覆盖create()
中的views.py
。仅使用此选项,并根据需要覆盖序列化程序的create()
方法(我认为这是DRF的良好策略)
class EmployeeCreateView(generics.CreateAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
请求有效负载
{
"user": "user data",
"tax_id_number": 12344,
"bio": {
"field1": "foo",
"field2": "bar"
},
"other fields": "values"
}