带有嵌套对象Django Rest Framework的ModelViewSet上的POST

时间:2018-08-06 14:34:53

标签: python django post django-models django-rest-framework

我正在使用django rest框架构建API。我有这些模型:

class Organisme(models.Model):
    nom = models.CharField(max_length=255)
    adresse = models.ForeignKey(Adresse, on_delete=models.CASCADE)

class Adresse(models.Model):
    rue = models.CharField(max_length=255, blank=True)

这是我的模式有机体的视图:

class OrganismeViewSet(viewsets.ModelViewSet):
    queryset = Organisme.objects.all()
    serializer_class = OrganismeSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = OrganismeFilter
    search_fields = ('nom')

我的序列化器:

class OrganismeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Organisme
        fields = '__all__'
        depth = 1

因此,我正在尝试通过发送以下内容来创建新的 Organisme

{
    "adresse": {
        "rue": "test"
    },
    "nom":"TestTest",
}

{
    "adresse": pk_id,
    "nom":"TestTest",
}

但我总是会遇到此错误:

IntegrityError at /organismes/
(1048, "Column 'adresse_id' cannot be null")

如果你们知道如何进行操作……谢谢。

1 个答案:

答案 0 :(得分:3)

您需要重写create方法以使writable nested serializer

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Addresse
        fields = ('rue',)

class OrganismeSerializer(serializers.ModelSerializer):
    addresse = AddressSerializer()

    class Meta:
        model = Organisme
        fields = '__all__'

    def create(self, validated_data):
        address_data = validated_data.pop('adresse')
        address = Adresse.objects.create(**address_data)
        organism = Organisme.objects.create(address=address, **validated_data)
        return organism