假设我们有这样的模型
class Product(models.Model):
name = models.CharField(max_length=100)
# ...
main_photo = models.ImageField(upload_to='photos/')
class ProductPhoto(models.Model):
product = models.ForeignKey(Product, related_name='photos', on_delete=models.CASCADE)
photo = models.ImageField(upload_to='photos/')
def __str__(self):
return self.photo.url
我有两种看法:
ProductsView
。它提供产品列表,其中包含每种产品的一般信息,仅包括name
、...
、main_photo
李>ProductDetailsView
。它提供了更详细的信息,包括所有照片李>class ProductsView(ListAPIView):
serializer_class = ProductSerializer
class ProductDetailsView(RetrieveAPIView):
serializer_class = ProductDetailsSerializer
序列化程序:
class ProductSerializer(ModelSerializer):
class Meta:
model = Product
fields = ('id', 'name', 'main_photo')
class ProductDetailsSerializer(ModelSerializer):
photos = StringRelatedField(many=True)
class Meta:
model = Product
fields = ('id', 'name', 'main_photo', 'photos')
我希望详细视图提供平面阵列photos
中的所有照片,如下[main_photo, ...rest_photos]
。
换句话说,,
响应详细视图而不是此视图:
{
"id": 1,
"name": "name",
"main_photo": "/media/photos/main_photo.jpg",
"photos": [
"/media/photos/photo1.jpg",
"/media/photos/photo2.jpg",
"/media/photos/photo3.jpg"
],
}
我想得到这个:
{
"id": 1,
"name": "name",
"photos": [
"/media/photos/main_photo.jpg",
"/media/photos/photo1.jpg",
"/media/photos/photo2.jpg",
"/media/photos/photo3.jpg"
],
}
如何使用django rest框架实现这一点?这个逻辑应该在哪个层次上实现?模型、视图、序列化程序
我想它应该在这里的某个地方,但不太确定它应该是什么样子
class ProductDetailsView(RetrieveAPIView):
serializer_class = ProductDetailsSerializer
def get_queryset(self):
query_set = Product.objects.all()
# ...
return query_set
对于照片的url,在
ProductPhoto
中添加一个__str__
方法,该方法将只返回照片的url然后像这样改变
ProductDetailsSerializer
有关DRFcheck this的更多关系相关文档
相关问题 更多 >
编程相关推荐