Django db field not displaying modified slug field value after serializing

Viewed 78

I am trying get the user names instead of user id, in the created_by field of the Comment class. My model is below:

class Comment(models.Model):
    thread_id = models.ForeignKey(Thread, on_delete=models.CASCADE)
    content = models.TextField()
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    likes = models.IntegerField(default=0)

Have used slugfield in the serializer.

class CommentSerializer(serializers.ModelSerializer):
    created_by = serializers.SlugRelatedField( 
                        slug_field='email',
                        queryset=User.objects.all())
    class Meta:
        model = Comment
        fields = ("id", "thread_id", "content", "created_by", "created_at", "likes")

Where as in the api below, the field created_by still has user id and not email.

 @action(detail=True, methods=["GET"])
    def list_comments(self, request, pk):
        comments = Comment.objects.filter(
            thread_id = pk
        )
        data = json.loads(serialize('json', comments))
        print("**************data**************")
        print(data)
        return Response(data, status.HTTP_200_OK)

The data printed looks like this :

[{'model': 'blog.comment', 'pk': 20, 'fields': {'thread_id': 19, 'content': 'hi', 'created_by': 2, 'created_at': '2021-07-14T03:34:11.333Z', 'likes': 0}}]

Is this because of serialize? How do I correctly get the value of the created_by as user email and not id ?

1 Answers

Use to_representation() method on the serializer

def to_representation(self, instance):
    rep = super(CommentSerializer, self).to_representation(instance)
    rep['created_by'] = instance.created_by.email
    return rep
Related