Tyler Dee
Tyler Dee

Reputation: 37

Django model - how to display class' property with foreign key in rest api

serializers.py:

class PostSerializer(ModelSerializer):
    class Meta:
        model=Post
        fields=[
            'author',
            'title',
            'content',
            'likes',
        ]

models.py:

class User(models.Model):

    name=models.CharField(max_length=255)
    surname=models.CharField(max_length=255)
    email=models.EmailField(max_length=255)
    username=models.CharField(max_length=255)
    password=models.CharField(max_length=2048)
    logged_in=models.BooleanField(default=False)

    def __str__(self):
        self.full_name=self.name+' '+self.surname
        return self.full_name


class Post(models.Model):
    author=models.ForeignKey(User,on_delete=models.CASCADE)
    title=models.CharField(max_length=255)
    content=models.TextField()
    likes=models.IntegerField(default=0)

My question is,

How would I display author.name from Post model class in Rest API via serializer, since serilizer fields take literal parameter name from the given class?

Upvotes: 0

Views: 493

Answers (1)

perfect5th
perfect5th

Reputation: 2062

Assuming you want a read-only field, a SerializerMethodField should do the trick. Try the following:

from rest_framework import serializers

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

    def get_author(self, obj):
        return obj.author.name

    class Meta:
        model=Post
        fields=[
            'author',
            'title',
            'content',
            'likes',
        ]

Upvotes: 1

Related Questions