4

我有以下两个类,我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/"
                }
            }
        }
    ]
}

在城市字段中,它返回城市的idmeta。如何在不进行额外查询的情况下在此处获取响应中的城市名称?:/

我在文档中找不到任何解决方案。我错过了什么吗?

4

2 回答 2

6

使用 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

检查Term Property以更好地理解这个概念

于 2015-12-15T13:01:38.460 回答
2

如果您在 Streamfield 中有外键,例如 PageChooserBlock,您可以通过覆盖块的 来自定义 api 响应,如此处提供get_api_representation示例中所述:

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
于 2018-09-10T09:56:34.017 回答