'Connetc two serializers to output general data

I can't output general data from two tables.

I am new to django rest framework and I have a question in regards of connecting two serializers in which have no connection each other from a model perspective.

For example, one is named CarouselWidget and other Image.

models.py

class CarouselWidget(models.Model):
    name = models.CharField(max_length=255, default='carousel_instance')
    widget_type = models.CharField(max_length=50, default='carousel', editable=False)

class Image(models.Model):
    name = models.CharField(max_length=255, default='image_instance')
    image = models.ImageField(upload_to='images/')
    default = models.BooleanField(default=False)
    carousel = models.ForeignKey(CarouselWidget, on_delete=models.CASCADE)

The serializers is built as follow:

serializers.py

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = ['image', 'carousel']

class CarouselWidgetSerializer(serializers.HyperlinkedModelSerializer):
    images = ImageSerializer(many=True, read_only=True)

    def create(self, validated_data):
        images_data = self.context['request'].FILES
        carousel = CarouselWidget.objects.create(
            widget_type=validated_data.get('widget_type', 'carousel')
        )
        for image_data in images_data.getlist('file'):
            Image.objects.create(carousel=carousel, image=image_data)

        return carousel

    class Meta:
        model = CarouselWidget
        lookup_field = 'id'
        fields = ['id', 'name', 'widget_type', 'images']

views.py

class CarouselWidgetList(generics.ListCreateAPIView):
    queryset = CarouselWidget.objects.all()
    serializer_class = CarouselWidgetSerializer

The actual outcome:

I have

What I am trying to do:

{
    "id": 2,
    "name": "carousel_instance",
    "widget_type": "carousel",
    "images": ["/some_path/", "/some_path/"] 
}

Basically, how do I link them together without the need of creating a new field in the model? As you can see I am trying to display the image into the CarouselWidget endpoint as shown above.



Solution 1:[1]

I've had to add the related_name to Image for ForeignKey:

carousel = models.ForeignKey(CarouselWidget, related_name='images' on_delete=models.CASCADE)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hagai Harari