我要使用JSON发送图像数组,如下所示:
{"id":1,"timeIntervel":4,"images":["http://127.0.0.1:8000/images/i1.jpg","http://127.0.0.1:8000/images/i2.jpg","http://127.0.0.1:8000/images/i3.jpg","http://127.0.0.1:8000/images/i4.jpg","http://127.0.0.1:8000/images/i5.jpg"]}
我用外键对模型进行了尝试。但未能获得上述答复。
model.py
class slidesModel(models.Model):
images = models.ImageField(upload_to='')
def __str__(self):
return str(self.images.name)
class slideImageArrayModel(models.Model):
timeIntervel=models.IntegerField()
images = models.ForeignKey(slidesModel, on_delete = models.CASCADE)
def __str__(self):
return str(self.id)
serializer.py
class slideSerializer(serializers.ModelSerializer):
class Meta:
model = slidesModel
fields='__all__'
class slideImgArraySerializer(serializers.ModelSerializer):
class Meta:
model = slideImageArrayModel
fields='__all__'
depth = 1
views.py
class slidesViewSet(viewsets.ViewSet):
def retrieve(self, request, pk=None):
queryset = slideImageArrayModel.objects.all()
user = get_object_or_404(queryset, pk=1) #it will always sends the first object
serializer = slideImgArraySerializer(user)
return Response(serializer.data)
我现有的输出需要一些修改才能实现实际输出:
{
"id": 1,
"timeIntervel": 4,
"images": {
"id": 8,
"images": "/images/b1.jpg"
}
}
我正在localhost中对此进行测试,并且未显示完整的url。我已经在设置和urls.py中包含了MEDIA_ROOT网址