How to show foreign key data values instead of urls in Django api?


I have the following codes in

class Tag(models.Model):
    name = models.CharField(max_length=40)

    def __str__(self):

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
    likes = models.IntegerField()
    popularity = models.FloatField()
    reads = models.IntegerField()
    tags = models.ManyToManyField(Tag)

class User(models.Model):
    name = models.CharField(max_length=40)
    def __str__(self):

but in localhost:8000/posts, I found out something weird: those foreign keys are shown as the urls, for example

        "url": "",
        "likes": 3,
        "popularity": 0.25,
        "reads": 59,
        "author": "",
        "tags": [

So in this case, how can I change the displayed api into something like "author":"Any Name" and "tags": ["tag1","tag2"] instead?


You can use ModelSerializer with SerializerMethodField

class YourSerializer(serializers.ModelSerializer):
  author = serializers.SerializerMethodField("get_author")
  tags = serializers.SerializerMethodField("get_tags")

  class Meta:
    model = YourModel
    fields = (YourModelFields, "author", "tags")

  def get_author(self,obj):

  def get_tags(self, obj):
    return obj.tags.all().values("name")

Answered By – Deepak Tripathi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published