我正在用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
因此,我正试图通过发送以下信息来创建一个新的有机体:
{
"adresse": {
"rue": "test"
},
"nom":"TestTest",
}
或
{
"adresse": pk_id,
"nom":"TestTest",
}
但我最终总是会出现这样的错误:
IntegrityError at /organismes/
(1048, "Column 'adresse_id' cannot be null")
如果你们知道如何继续。。。提前谢谢。
您需要重写create
方法以使嵌套序列化程序可写:
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