我正在尝试使用可写的嵌套序列化程序在Django Rest Framework中执行创建。
使用下面的代码,我想创建调度程序,但是不允许我创建调度程序。 我在创建序列化程序时发生了什么错误,从而不允许我创建调度程序。
谢谢!!!
Serializers.py
from django.contrib.auth import get_user_model
from rest_framework import serializers
from dispatcher.models import Dispatcher
from dispatcher.models import DispatacherDocument
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'password',)
class documentserializers(serializers.ModelSerializer):
class Meta:
model = DispatacherDocument
fields = [
'dispatcher_document'
]
read_only = True
Dispatcherserializers(serializers.ModelSerializer):
dispatcher_document = documentserializers(required=False)
user = UserSerializer(required=True)
class Meta:
model = Dispatcher
fields = [
"user",
"disptacher_email",
"disptacher_type",
"phone_number",
"address",
"pan_number",
"company_type",
"dispatcher_document",
]
def create(self, validated_data):
user_data = validated_data.pop('user')
user = UserSerializer.create(UserSerializer(), validated_data=user_data)
dispatcher_data = validated_data.pop('dispatcher_document ')
dispatcher_document = documentserializers.create(documentserializers(), validated_data=dispatcher_data)
print(validated_data)
dispatcher, created = Dispatcher.objects.update_or_create(user=user,
dispatcher_document=dispatcher_document,
disptacher_email=validated_data.get(
'dispatcher_email'),
disptacher_type=validated_data.get(
'dispatcher_type'),
phone_number=validated_data.get('phone_number'),
address=validated_data.get('address'),
pan_number=validated_data.get('pan_number'),
company_type=validated_data.get('company_type'),
)
return dispatcher