我在app.models
中有以下两个类,我使用wagtail API将数据作为json
class AuthorMeta(Page):
author=models.OneToOneField(User)
city = models.ForeignKey('Cities', related_name='related_author')
class Cities(Page):
name = models.CharField(max_length=30)
因此,当我尝试/api/v1/pages/?type=dashboard.AuthorMeta&fields=title,city
时,它会返回以下数据:
{
"meta": {
"total_count": 1
},
"pages": [
{
"id": 11,
"meta": {
"type": "dashboard.AuthorMeta",
"detail_url": "http://localhost:8000/api/v1/pages/11/"
},
"title": "Suneet Choudhary",
"city": {
"id": 10,
"meta": {
"type": "dashboard.Cities",
"detail_url": "http://localhost:8000/api/v1/pages/10/"
}
}
}
]
}
在城市字段中,它会返回城市的id
和meta
。如何在此处获取响应中的城市名称,而无需进行额外查询? :/
我无法在Documentation中找到任何解决方案。我错过了什么吗?
答案 0 :(得分:4)
使用Django model属性返回ForeignKey:
class AuthorMeta(Page):
author=models.OneToOneField(User)
city = models.ForeignKey('Cities', related_name='related_author')
city_name = property(get_city_name)
def get_city_name(self):
return self.city.name
检查Term Property以更好地理解概念
答案 1 :(得分:2)
如果您在Streamfield中有外键,例如PageChooserBlock,您可以通过覆盖块的get_api_representation
来自定义api响应,如示例here中所述:
class CustomPageChooserBlock(blocks.PageChooserBlock):
""" Customize the api response. """
def get_api_representation(self, value, context=None):
""" Return the url path instead of the id. """
return value.url_path