如何在 Django api 中显示外键数据值而不是 url?
How to show foreign key data values instead of urls in Django api?
我在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
但是在localhost:8000/posts中,我发现了一些奇怪的东西:那些外键显示为url,例如
{
"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/"
]
}
所以在这种情况下,如何将显示的 api 更改为 "author":"Any Name"
和 "tags": ["tag1","tag2"]
之类的内容?
您可以将 ModelSerializer
与 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")
我在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
但是在localhost:8000/posts中,我发现了一些奇怪的东西:那些外键显示为url,例如
{
"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/"
]
}
所以在这种情况下,如何将显示的 api 更改为 "author":"Any Name"
和 "tags": ["tag1","tag2"]
之类的内容?
您可以将 ModelSerializer
与 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")