P
P
Pan Propan2021-09-08 14:24:32
Django
Pan Propan, 2021-09-08 14:24:32

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)


and there are 2 serializers
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__'


How can I get the url of images related to a product in the ProductListSerializer ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pan Propan, 2021-09-08
@mgis

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

S
Stefan, 2021-09-08
@MEDIOFF

Tyk , here are examples of different implementations, and you can completely serialize the model and part of it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question