2

Before calling this a repeat question please have a look at my code.

I have a Blog Model and here is the Favourites part of it:

class Fav(models.Model) :
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    class Meta:
        unique_together = ('post', 'user')

    def __str__(self) :
        return str(self.user.username)

My serializer looks like this:

class FavSerializer(serializers.ModelSerializer):
    class Meta:
        model = Fav
        fields = ['post', 'user']

I assumed because of the __str__ part, that this API will return the username but instead it returns only the user_id. How can I return the username?

Zayyan Masud
  • 135
  • 1
  • 12
  • This would help you [How do I include related model fields using Django Rest Framework?](https://stackoverflow.com/questions/14573102/how-do-i-include-related-model-fields-using-django-rest-framework) – Abdul Aziz Barkat Feb 03 '21 at 15:38

1 Answers1

5

Do this

class FavSerializer(serializers.ModelSerializer):
    user = serializer.CharField()
    class Meta:
        model = Fav
        fields = ['post', 'user']
lord stock
  • 1,191
  • 5
  • 32