Python 如何在Wagtail(django)中访问ForeignKey数据而不进行额外查询
在我的Python 如何在Wagtail(django)中访问ForeignKey数据而不进行额外查询,python,django,django-models,wagtail,Python,Django,Django Models,Wagtail,在我的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) 因此,当我
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
。我怎样才能在这里的回复中获得城市的名称,而不需要进行额外的查询/
我在这个问题上找不到任何解决办法。我遗漏了什么吗?使用Django模型属性通过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
检查以更好地理解概念如果您在Streamfield(例如PageChooserBlock)中有外键,您可以通过覆盖块的
get\u api\u表示来自定义api响应,如所提供示例中所述:
这很有效,但是多对一关系呢。
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