Home > Back-end >  I am unable to serialize my product images in Django Rest Framework
I am unable to serialize my product images in Django Rest Framework

Time:12-14

I am trying to create product model for my e-commerce app in Django rest framework, and I am able to upload images to my products on the admin panel but I am unable to get their links while calling the API. Here's my:

models.py

from django.db import models
from api.category.models import Category
from api.color.models import Color
from api.size.models import Size


class Product(models.Model):
    name = models.CharField(max_length=50)
    description = models.CharField(max_length=250)
    regular_price = models.CharField(max_length=50)
    sell_price = models.CharField(max_length=50, blank=True, null=True)
    stock = models.CharField(max_length=50)
    is_active = models.BooleanField(default=True, blank=True)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL,  blank=True, null=True)
    colors = models.ManyToManyField(Color)
    sizes = models.ManyToManyField(Size)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


    def __str__(self) -> str:
        return self.name
class ProductImage(models.Model):
    product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE)
    image = models.FileField(upload_to = 'images/')
 
    def __str__(self):
        return self.image.url

serializer.py

from django.db.models import fields
from rest_framework import serializers

from .models import Product, ProductImage


class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductImage
        fields = ('image', )
        #print(model)
        
class ProductSerializer(serializers.HyperlinkedModelSerializer):
    colors = serializers.StringRelatedField(many=True)
    sizes = serializers.StringRelatedField(many=True)
    image = ImageSerializer(many=True, read_only=True)
    class Meta:
        model = Product
        fields = ('id', 'name', 'description', 'regular_price', 'sell_price', 'category','colors', 'sizes', 'image')

admin.py

from django.contrib import admin
from .models import Product, ProductImage


class ProductImageAdmin(admin.StackedInline):
    model = ProductImage
 
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    inlines = [ProductImageAdmin]
 
    class Meta:
       model = Product
 
@admin.register(ProductImage)
class ProductImageAdmin(admin.ModelAdmin):
    pass

view.py

from rest_framework import viewsets
from .serializers import Product, ProductSerializer, ImageSerializer
from .models import Product, ProductImage
from . import serializers


class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all().order_by('id')
    serializer_class = ProductSerializer

urls.py

from rest_framework import routers
from django.urls import path, include


from . import views

router = routers.DefaultRouter()
router.register(r'', views.ProductViewSet)
urlpatterns = [
    path('', include(router.urls))
]

Here's How it looks like on admin panel.

enter image description here

enter image description here

but I can not get the links of images while calling the API as shown in next image.

enter image description here

CodePudding user response:

First update your ProductImage model: Add a related name for this relation

class ProductImage(models.Model):
    ...
    product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE, related_name="product_images")

Change your serializer to this:

class ProductSerializer(serializers.HyperlinkedModelSerializer):
   colors = serializers.StringRelatedField(many=True)
   sizes = serializers.StringRelatedField(many=True)
   images = serializers.SerializerMethodField()

   def get_images(self, product):
       return ImageSerializer(product.product_images.all(), many=True).data

   class Meta:
       model = Product
       fields = ('id',..., 'images')
  • Related