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 [
]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
The problem with the TrainZoneSerializer is that
imagesisn't a field on the TrainZone model. When you declared thetrainzoneforeign key on the TrainZoneImage model, you didn't specify arelated_name. This means that by default, the attribute on the TrainZone model that references TrainZoneImage is calledtrainzoneimage_set. So if you replaceimageswithtrainzoneimage_setin your serializer, it should work.If you want to keep the serializer the same, you can alternatively add
related_name="images"to thetrainzoneForeignKey, which means thatimageswill be the name of the attribute on TrainZone that references TrainZoneImage, instead oftrainzoneimage_set.