Django休息框架更新模型的相关FileField

时间:2017-08-26 10:08:29

标签: django django-rest-framework

说我有这些模型:

class House(models.model):
    address = models.CharField(max_length=100)

class HouseImage(models.Model):
    image = models.ImageField(...)
    house = models.ForeignKey(House, related_name='images')

这个序列化器:

class HouseImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = HouseImage
        fields = ('image', )

class HouseSerializer(serializers.ModelSerializer):
    images = HouseImageSerializer(many=True, required=False)
    class Meta:
        model = House
        fields = ('address', 'images', )

这个观点:

class HouseDetails(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = HouseSerializer
    queryset = House.objects.all()

我正从我的前端拨打电话。一个人创造了房子(并且它起作用),第二个人应该发送图像。因此,在第二个电话中,我正在发送PATCH请求(使用axios),而我的request.data{'images': [InMemoryUploadedFile1, InMemoryUploadedFile2,...]}

问题:

  1. 到目前为止,通过在images上定义HouseSerializer字段,我做得对吗?如果它是正确的,我还应该做什么?因为我知道我需要以某种方式将imagesrequest.data列表中的每个图像映射到image中的HouseImage字段。

  2. 实施此方法有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

事实上你没有patchHouse模型,你试图创建新的HouseImage,所以在我看来,最好的方法是HouseImage模型的新APIView。 / p>

在序列化器中:

class HouseImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = HouseImage
        fields = ('image', 'house')
        #                   ^^^^^^

在视图中

class HouseImageDetails(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = HouseImageSerializer
    queryset = HouseImage.objects.all()
<{1>} HouseSerializer houseimages你会有额外的字段update吗?

对于您的情况,您可以尝试覆盖class HouseSerializer(serializers.ModelSerializer): images = HouseImageSerializer(many=True, required=False) class Meta: model = House fields = ('address', 'images', ) def update(self, instance, validated_data): request = self.context.get('request') images = request.data.get('images', []) if request else [] for img in images: data = {'image': img, 'house': instance} hiSerializer = HouseImageSerializer(data) if hiSerializer.is_valid(): hiSerializer.save() return super(HouseSerializer, self).update(instance, validated_data)

<NavigationView></NavigationView>