Taking field from another model in serializers

24 views Asked by At

Now Im doing a pet project about sports, and I have a TrainZone and TrainZoneImage model, and in serializers I need to display the image field from the TrainZoneImage model in TrainZoneSerializer

field images should be [enter image description here]where circled in black

`models.py from django.db import models from ckeditor.fields import RichTextField

class TrainZone(models.Model):

    title = models.CharField(max_length=100, verbose_name='Название')
    description = RichTextField(verbose_name='Описание')


    def __str__(self):
        return self.title



    class Meta:
        verbose_name = 'Тренировочная зона',
        verbose_name_plural = 'Тренировочные зоны'


class TrainZoneImage(models.Model):
    trainzone= models.ForeignKey(TrainZone, default=None, on_delete=models.CASCADE)
    images = models.FileField(upload_to='media/')

    def __str__(self):
        return self.trainzone.title`

`
serializers.py

from rest_framework import serializers

from .models import TrainZone, TrainZoneImage

class TrainZoneImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = TrainZoneImage
        fields = ('id', 'images')  # Измените поля по необходимости

class TrainZoneSerializer(serializers.ModelSerializer):
    images = TrainZoneImageSerializer(many=True, read_only=True)

    class Meta:
        model = TrainZone
        fields = ('id', 'title', 'description', 'images')

class TrainZoneValidatorSerializer(serializers.ModelSerializer):
    class Meta:
        model = TrainZone
        fields = '__all__'

`

I tried to take images from TrainZoneImage by making TrainZoneImageSerializer and taking field images in TrainZone Serializer

1

There are 1 answers

0
schwartz721 On

The problem with the TrainZoneSerializer is that images isn't a field on the TrainZone model. When you declared the trainzone foreign key on the TrainZoneImage model, you didn't specify a related_name. This means that by default, the attribute on the TrainZone model that references TrainZoneImage is called trainzoneimage_set. So if you replace images with trainzoneimage_set in your serializer, it should work.

If you want to keep the serializer the same, you can alternatively add related_name="images" to the trainzone ForeignKey, which means that images will be the name of the attribute on TrainZone that references TrainZoneImage, instead of trainzoneimage_set.