0

From my little knowledge on how serializers work, I know we mostly use modelserializers, and for that, we would have a model for all we want to serialize but how can I join all the images in the different models and then serialize them.

These are my models

class Vendors(models.Model):
    title = models.CharField(max_length=50, blank=False)
    image = models.ImageField(upload_to='static/vendors', blank=True, null=True)

class Riders(models.Model):
    title = models.CharField(max_length=50, blank=False)
    image = models.ImageField(upload_to='static/riders', blank=True, null=True)

class VendorsRiders(models.Model):
    VendorImg = models.ForeignKey(Vendors, on_delete=models.CASCADE)
    RiderImg = models.ForeignKey(Riders, on_delete=models.CASCADE)

This is my serializer

Class VendorsRidersSerializers(models.Model):
    Class Meta:
           model = VendorsRiders
           fields = '__all__'

So, how to get all the images to the endpoint i would specify ? since, I'm a beginner in DRF I also need a suggestion and advice on the best practice to do this. Thank you

Willy satrio nugroho
  • 908
  • 1
  • 16
  • 27

1 Answers1

0

With defining fields = '__all__' in a serializer you just have access to properties of your model. One way to serialize your image fields of related models is to define SerializerMethodField Like:

Class VendorsRidersSerializers(models.Model):
    rider_image = serializers.SerializerMethodField()

    Class Meta:
           model = VendorsRiders
           fields = '__all__'

    def get_rider_image(self, obj):
        req = self.context['request']
        # build_absolute_uri will convert your related url to absolute url
        return req.build_absolute_uri(obj.VendorImg.image.url)

Also note that you should pass the request from your view to context of your serializer to build an absolute url (Example: VendorsRidersSerializers(queryset, many=True, context={'request': self.request}) or override the get_serializer_class method and pass the request to it's context) and then use the data of this serializer.

Roham
  • 1,970
  • 2
  • 6
  • 16
  • i was able to do that and get the image url path but now, i am no longer able to post/edit a new image. And also i dont undertand what the note you left above here is a look at my view '''from .serializers import * from rest_framework import generics class ImageList(generics.ListCreateAPIView): queryset = ImageModel.objects.all() serializer_class = ImageModelSerializer class ImageDetail(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'id' queryset = ImageModel.objects.all() serializer_class = ImageModelSerializer ''' –  Sep 02 '20 at 23:26
  • What i actuallly what to do is make an endpoint that lists all the images in my projects. It should be able to get all the images from all fields in different table. Please do you have any idea about i can go about that. Thanks in advance –  Sep 04 '20 at 00:01