我使用Django休息框架,我有一个问题:
我的模特:
class Store_Rotation(models.Model):
store = models.ForeignKey(Stores)
rotation = models.ImageField(upload_to='rotation/', verbose_name="轮播图")
def __str__(self):
return self.rotation.url
我的序列化器:
class Store_RotationSerializer(ModelSerializer):
class Meta:
model = Store_Rotation
fields = '__all__'
我的观点:
class Store_RotationViewSet(ModelViewSet):
queryset = Store_Rotation.objects.all()
serializer_class = Store_RotationSerializer
它返回:
[
{
"id": 1,
"rotation": "http://192.168.33.10:8000/files/rotation/%E4%B8%9A%E5%8A%A1%E6%B5%81%E7%A8%8B%E5%9B%BE.png",
"store": 1
}
]
我想要归还:
{
data:
[
{
"id": 1,
"rotation": "http://192.168.33.10:8000/files/rotation/%E4%B8%9A%E5%8A%A1%E6%B5%81%E7%A8%8B%E5%9B%BE.png",
"store": 1
}
]
}
怎么做? 它有一些通用的方法吗?
答案 0 :(得分:1)
您必须覆盖列表序列化程序类
上的to_representation方法定义一个列表序列化器类:
class StoreRotationListSerializer(serializers.ListSerializer):
def to_representation(self, data):
repr = super(StoreRotationListSerializer, self).to_representation(data)
return {'data': repr}
现在在主序列化程序中使用此列表序列化程序类:
class Store_RotationSerializer(ModelSerializer):
class Meta:
model = Store_Rotation
fields = '__all__'
list_serializer_class = StoreRotationListSerializer
在此处详细了解列表序列化程序:http://www.django-rest-framework.org/api-guide/serializers/#listserializer
答案 1 :(得分:0)