使用嵌套对象Django Rest Framework在ModelViewSet上放置PUT

时间:2018-08-07 00:16:07

标签: python django python-3.x django-models django-rest-framework

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

class Organism(models.Model):
    name = models.CharField(max_length=255)
    address = models.ForeignKey(Address, on_delete=models.CASCADE)
    type = models.ForeignKey(Type, on_delete=models.CASCADE)

class Address(models.Model):
    street = models.CharField(max_length=255, blank=True)

class Type(models.Model):
    name = models.CharField(max_length=255, blank=True)

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

class OrganismViewSet(viewsets.ModelViewSet):
    queryset = Organism.objects.all()
    serializer_class = OrganismSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = OrganismFilter
    search_fields = ('name')

我的序列化器:

class OrganismSerializer(serializers.ModelSerializer):
    addresse = AddressSerializer()
    type = TypeSerializer()
    class Meta:
        model = Organism
        fields = '__all__'

    def update(self, instance, validated_data):
        // What I should write to do something "elegant"

让我们想象一下,当我得到有机主义时,我有:

{
    "address": {
        "id": 1
        "street": "test"
    },
    type: {
        "id": 1,
        "name": "type Organism"
    },
    "name":"TestTest",
}

所以我正在尝试更新有机体(我想更改街道名称,但不创建新对象并更改存在于我的类型中数据库),方法如下:

{
    "address": {
        "id": 1
        "street": "new name"
    },
    type: {
        "id": 2,
        "name": "new type"
    }
    "name":"TestTest",
}

事实是我在方法更新的参数“ validated_data”中没有我的对象的ID。 如果你们知道如何进行...提前谢谢。

0 个答案:

没有答案