Zain Ur Rehman
Zain Ur Rehman

Reputation: 297

Unable to populate images in Django Rest Serializer

I'm developing a REST API using Django Rest Framework but I'm unable to populate image in Feed Serializer

Django Version: 3.1.7

Python Version: 3.9.2

Models:

class User(AbstractUser):
    age = models.PositiveIntegerField(null=True)
    address = models.TextField(null=True)
    email = models.EmailField(_('email address'), unique=True, null=False)
    first_name = models.CharField(_('first name'), max_length=150, blank=False, null=False)
    last_name = models.CharField(_('last name'), max_length=150, blank=False, null=False)
    image = models.ImageField(upload_to='storage', null=True)
    

class Feed(models.Model):
    description = models.TextField()
    likes_count = models.PositiveIntegerField(default=0, null=True)
    comments_count = models.PositiveIntegerField(default=0, null=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user')
    tags = models.ManyToManyField(User, related_name='tags', blank=True)


class FeedImage(models.Model):
    path = models.ImageField(upload_to='storage', null=False)
    post = models.ForeignKey(Feed, on_delete=models.CASCADE, null=False, default='')

Serializers:

      class FeedUserSerializer(ModelSerializer):
            class Meta:
                model = User
                fields = ('id', 'first_name', 'last_name', 'image')

      class FeedImageSerializer(serializers.ModelSerializer):
            class Meta:
                model = FeedImage
                fields = ('id', 'path', 'post')
    
      class FeedSerializer(ModelSerializer):
            user = FeedUserSerializer()
            images = FeedImageSerializer(many=True, read_only=True)
    
            class Meta:
                model = Feed
                fields = ('id', 'description', 'comments_count', 'likes_count', 'updated_at', 'created_at',
                      'tags', 'images', 'user')

View:

class FeedsListView(generics.ListAPIView):
    queryset = Feed.objects.all()
    return FeedSerializer

Problem: I get this result without images

[{
      "id": 1,
      "description": "Hello world",
      "comments_count": 0,
      "likes_count": 0,
      "updated_at": "2021-04-26T03:01:44.219235Z",
      "created_at": "2021-04-26T03:01:44.219235Z",
      "tags": [],
      "user": {
        "id": 1,
        "first_name": "ZAIN",
        "last_name": "REHMAN",
        "image": "http://192.168.88.28:8000/storage/1_Facebook_1.jpg"
      }
}]

Expected Output:

[{
      "id": 1,
      "description": "Hello world",
      "comments_count": 0,
      "likes_count": 0,
      "updated_at": "2021-04-26T03:01:44.219235Z",
      "created_at": "2021-04-26T03:01:44.219235Z",
      "tags": [],
      "user": {
        "id": 1,
        "first_name": "abc_first",
        "last_name": "cdef_last",
        "image": "http://192.168.88.28:8000/storage/1_Facebook_1.jpg"
      },
      "images": [
         {
            "id": 1,
            "post": "1",
            "path": "imagelocation"
         },
         {
            "id": 2,
            "post": "1",
            "path": "imagelocation 2"
         }
      ]
}]

Any solution or any workaround will be appreciated.

Ignore this: Bulk text to resolve StackOverflow problem industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Upvotes: 0

Views: 31

Answers (1)

Arjun Shahi
Arjun Shahi

Reputation: 7330

You can use SerializerMethodField for this.

  class FeedSerializer(ModelSerializer):

        images = serializers.SerializerMethodField()

        class Meta:
            model = Feed
            fields = ('id', 'description', 'comments_count', 'likes_count', 'updated_at', 'created_at',
                  'tags', 'images', 'user')
        
        def get_images(self, obj):
            return obj.feedimage_set.all().values('id', 'path', 'post')

Upvotes: 1

Related Questions