我正在尝试在Django Rest Framework中创建可写的嵌套序列化程序。但是我收到验证错误:slug
是必需的。但这是外键,在插入父对象之前未知。
这是我的模型和序列化器:
型号:
class Letter(BaseModel):
char = models.CharField(
max_length=1,
)
slug = models.ForeignKey(
to="core.LetterSlug",
related_name="letters",
on_delete=models.CASCADE,
)
class LetterSlug(BaseModel):
char = models.CharField(
max_length=1,
)
序列化器:
class LetterSerializer(serializers.ModelSerializer):
class Meta:
model = Letter
fields = '__all__'
class LetterSlugSerializer(serializers.ModelSerializer):
letters = LetterSerializer(many=True,instance=Letter.objects.all())
class Meta:
model = LetterSlug
fields = ('char', 'letters')
def create(self, validated_data):
letter_data = validated_data.pop('letters')
slug = LetterSlug.objects.create(**validated_data)
Letter.objects.create(slug=slug, **letter_data)
return slug
我希望它向新创建的Letter
对象添加几个LetterSlug
对象,这些对象共享相同的外键。
我尝试注释掉create方法的内容,并确保它在验证过程中,然后再调用create方法。
答案 0 :(得分:0)
只需在LetterSerializer中将子弹设为只读:
class LetterSerializer(serializers.ModelSerializer):
class Meta:
model = Letter
fields = '__all__'
read_only_fields = ("slug", )
还如下编辑您的其他序列化器:
class LetterSlugSerializer(serializers.ModelSerializer):
letters = LetterSerializer(many=True)
class Meta:
model = LetterSlug
fields = ('char', 'letters')
def create(self, validated_data):
letters_data = validated_data.pop('letters')
slug = super().create(**validated_data)
Letter.objects.bulk_create([ Letter(slug=slug, **letter) for letter in letters_data ])
return slug