在序列化程序中格式化JSON-Django REST
我是Django和Django REST的新手,我的任务是创建一个序列化程序。 我的序列化程序的输出如下所示:在序列化程序中格式化JSON-Django REST,json,django,django-rest-framework,django-serializer,Json,Django,Django Rest Framework,Django Serializer,我是Django和Django REST的新手,我的任务是创建一个序列化程序。 我的序列化程序的输出如下所示: { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "name": "a", "description": "a", "price": "1.00", "images": [ {
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"name": "a",
"description": "a",
"price": "1.00",
"images": [
{
"image_addr": "http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_15-07-34.png",
"product": 1
},
{
"image_addr": "http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_16-42-55.png",
"product": 1
}
]
}
]
}
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"name": "a",
"description": "a",
"price": "1.00",
"images": [
"http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_15-07-34.png",
"http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_16-42-55.png"
]
}
]
}
我如何调整序列化程序,使其输出如下所示:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"name": "a",
"description": "a",
"price": "1.00",
"images": [
{
"image_addr": "http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_15-07-34.png",
"product": 1
},
{
"image_addr": "http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_16-42-55.png",
"product": 1
}
]
}
]
}
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"name": "a",
"description": "a",
"price": "1.00",
"images": [
"http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_15-07-34.png",
"http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_16-42-55.png"
]
}
]
}
我正在使用的序列化程序有:
class ProductImageSerializer(serializers.ModelSerializer):
class Meta:
model = ProductImage
fields = ('image_addr', 'product')
及
我使用的型号是:
class ProductImage(models.Model):
image_addr = models.FileField(upload_to='products/',null=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
及
我的看法是:
class CategoryProductList(generics.ListAPIView):
serializer_class = ProductSerializer
def get_queryset(self):
queryset = Product.objects.filter(category__id=self.kwargs['pk'])
return queryset
你可以为你的目的使用。按如下所示更改ProductSerializer
您可以添加您的产品和ProductImage型号吗?很高兴能帮助您:
class ProductSerializer(serializers.ModelSerializer):
images = serializers.SerializerMethodField(read_only=True, source='images')
def get_images(self, model):
return model.images.values_list('image_addr', flat=True)
class Meta:
model = Product
fields = ('id', 'name', 'description', 'price', 'images')