如何从一个端点创建或更新多个不同模型的对象

时间:2019-04-15 11:13:51

标签: django django-rest-framework

如何从一个端点更新多个不同模型类型的对象。我尝试了很多方法,但仍然失败。我尝试了嵌套序列化程序和create方法,但仍然无法正常工作

class Student(models.Model):
    name = models.CharField(max_length=300)
    sex  = models.CharField(choices=SEX_CHOICES,max_length=255, 
    null=True)
    Category = models.CharField(max_length=100, null=True)

    def __str__(self):
    return self.name


class Registration(models.Model):
    registration_no = models.CharField(max_length=255, 
    unique=True)
    student = models.OneToOneField(Student, 
    on_delete= models.CASCADE, related_name='registrations')

    def __str__(self):
        return self.registration_no

class RegistrationSerializer(serializers.ModelSerializer):

    class Meta:
        model = Registration
        fields = '__all__'    

class StudentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Student
        fields = '__all__'

class StudentDataMigrateSerializer(serializers.Serializer):
    student = StudentSerializer()
    registation = RegistrationSerializer()

1 个答案:

答案 0 :(得分:0)

默认情况下,在Django Rest框架中,嵌套的序列化器是只读的。要拥有可写的嵌套序列化程序,您需要实现create()和/或update()方法。 看看官方文档https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers

class StudentDataMigrateSerializer(serializers.Serializer):
    student = StudentSerializer()
    registation = RegistrationSerializer()

    def create(self, validated_data):
        # save the data