Max Price
Max Price

Reputation: 15

Formatting JSON in Serializer - Django REST

I am new to Django and Django-REST and I was tasked to create a serializer. The output of my serializer looks like this:

    {
"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
            }
        ]
    }
]
}

How can i tweak my serializer in a way that my output would look like this:

   {
"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"
        ]
    }
]
}

The serializers that I am using are:

    class ProductImageSerializer(serializers.ModelSerializer):
        class Meta:
            model = ProductImage
            fields = ('image_addr', 'product')

and

    class ProductSerializer(serializers.ModelSerializer):
        images = ProductImageSerializer(many=True, read_only=True)
        class Meta:
            model = Product
            fields = ('id', 'name', 'description', 'price','images')

My models used are:

    class ProductImage(models.Model):
        image_addr = models.FileField(upload_to='products/',null=True)
        product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')

and

    class Product(models.Model):
        name = models.CharField(max_length=150)
        price = models.DecimalField(max_digits=9, decimal_places=2)
        product_count = models.IntegerField(blank=True, default=0, validators=[MinValueValidator(0)])
        description = models.TextField()
        category = models.ManyToManyField(Category)
        objects = ProductManager()

My view used is:

    class CategoryProductList(generics.ListAPIView):
        serializer_class = ProductSerializer

        def get_queryset(self):
            queryset = Product.objects.filter(category__id=self.kwargs['pk'])
            return queryset

Upvotes: 0

Views: 779

Answers (1)

JPG
JPG

Reputation: 88689

You can use SerializerMethodField for your purpose.

Change your ProductSerializer as below

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')

Upvotes: 1

Related Questions