说我有这些模型:
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,...]}
问题:
到目前为止,通过在images
上定义HouseSerializer
字段,我做得对吗?如果它是正确的,我还应该做什么?因为我知道我需要以某种方式将images
中request.data
列表中的每个图像映射到image
中的HouseImage
字段。
实施此方法有更好的方法吗?
答案 0 :(得分:1)
事实上你没有patch
你House
模型,你试图创建新的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
house
中images
你会有额外的字段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>