Answer the question
In order to leave comments, you need to log in
How to get related field in Django serializer?
There are 2 models.
сlass Product(models.Model):
name = models.CharField(verbose_name='Наименование товара', max_length=120)
slug = models.SlugField(verbose_name='URL товара', blank=True, unique=True)
description = models.TextField(verbose_name='Описание')
price = models.DecimalField(verbose_name='Цена', decimal_places=2, max_digits=20, default=0)
class ProductImage(models.Model):
image = models.ImageField(upload_to='products/%Y/%m/%d')
product = models.ForeignKey(Product, default=None, related_name='images', on_delete=models.PROTECT)
class ProductListSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'name', 'slug', 'price', 'category', 'images']
read_only_fields = fields
class ProductImagesSerializers(serializers.ModelSerializer):
class Meta:
model = ProductImage
fields = '__all__'
Answer the question
In order to leave comments, you need to log in
class ProductImagesSerializers(serializers.ModelSerializer):
class Meta:
model = ProductImage
fields = '__all__'
class ProductListSerializer(serializers.ModelSerializer):
images = ProductImagesSerializers(many = True, read_only = True)
class Meta:
model = Product
fields = ['id', 'name', 'slug', 'price', 'category', 'images']
read_only_fields = fields
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question