简体   繁体   中英

How to return username instead of ID

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?

Do this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM