Home > Net >  Django model rendering number instead of string
Django model rendering number instead of string

Time:05-19

I'm creating a blog site with authors posting blogs, etc. The issue is with rendering the author's name, instead django is returning a number.

My blog model:

class Blog(models.Model):
    title=models.CharField(max_length=255)
    author=models.ForeignKey(User, on_delete=models.CASCADE)
    date_posted=models.DateTimeField(auto_now_add=True)
    body=models.TextField()

    def __str__(self):
        return self.title

And my serializer:

    class Meta:
        model=Blog
        fields=('title', 'author', 'body', 'date_posted')

However, in django rest framework it's rendering a number, when it should be the 'admin' user:

[
{
        "title": "First Blog",
        "author": 1,
        "body": "Example blog text",
        "date_posted": "2022-05-18T23:55:21.529755Z"
    }
]

A bit confused, since there's no error, it just isn't rendering 'admin'. Any help would help thanks.

CodePudding user response:

It is showing the primary key of the User object, which is what is stored in a foreign key field.

To follow that through to the User objects username (and assuming you don't have a User serializer), you could create a custom field, eg,

class Meta:
    model=Blog
    fields=('title', 'author', 'author_name', 'body', 'date_posted')

author_name = serializers.SerializerMethodField('get_author_name')

def get_author_name(self, obj):
    return obj.author.username

CodePudding user response:

To get the full author data, you need to add the UserSerializer in BlogSerializer.

class BlogSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only = True)

    class Meta:
        model = Blog
        fields = ('title', 'author', 'author_name', 'body', 'date_posted', )

Hope it could help.

  • Related