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

Time:05-06

I have the following codes in models.py

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

    def __str__(self):
        return self.name

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):
        return self.name

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

{
        "url": "http://127.0.0.1:8000/posts/1/",
        "likes": 3,
        "popularity": 0.25,
        "reads": 59,
        "author": "http://127.0.0.1:8000/users/1/",
        "tags": [
            "http://127.0.0.1:8000/tags/1/",
            "http://127.0.0.1:8000/tags/2/"
        ]
    }

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

CodePudding user response:

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):
    return obj.author.name

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