Home > database >  How to include user's image in Post instance
How to include user's image in Post instance

Time:12-14

I have a view that returns me every post, what I'm trying to do is include the user's avatar image with the post.

Serializer

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

View

@api_view(['GET'])
def getPost(request):
    post = Post.objects.all().order_by('-date_posted')
    serializer = PostSerializer(post, many=True)
    return Response(serializer.data)

User Model

class User(AbstractBaseUser):
    email = models.EmailField(verbose_name="email", max_length=60, unique=True)
    username = models.CharField(max_length=30, unique=True)
    avatar = models.ImageField(default='default.jpg')

Post Model

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=CASCADE)
    trade = models.CharField(max_length=100)
    trade_description = models.TextField(null=True)

How can I make it so that when the view returns me the post, it also includes the associated user's avatar image as well? The User's avatar field just holds a link to an amazon s3 bucket that hosts the image

CodePudding user response:

There is two ways

1. Nested serializer

It gives you nested response

Declare a serializer for user, then include it in your post serializer:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('avatar', ...)


class PostSerializer(serializers.ModelSerializer):
    author = UserSerializer()

    class Meta:
        model = Post
        fields = '__all__'

2. Use source

It gives you flat response

class PostSerializer(serializers.ModelSerializer):
    author_avatar = serializers.ImageField(source='author.avatar')

    class Meta:
        model = Post
        fields = ('author_avatar', ...)
  • Related