0

我的 app.models 中有以下两个类,我正在使用 wagtail API 将数据作为 json

class States(Page):
    name=models.CharField(max_length=50)

class Cities(Page):
    def get_state_name(self):
        return self.state.name
    name = models.CharField(max_length=50)
    state = models.ForeignKey(States, related_name='related_cities' )
    state_name = property(get_state_name)

因此,当我尝试 /api/v1/pages/?type=dashboard.States&fields=name,related_cities 时,它返回以下数据:

{
    "meta": {
        "total_count": 1
    },
    "pages": [
        {
            "id": 1,
            "name": "State1",
            "meta": {
                "type": "dashboard.States",
                "detail_url": "http://localhost:8000/api/v1/pages/2601/"
            },
            "related_cities": [
                {
                    "id": 28,
                    "meta": {
                        "type": "dashboard.Cities",
                        "detail_url": "http://localhost:8000/api/v1/pages/28/"
                    }
                },
                {
                    "id": 37,
                    "meta": {
                        "type": "dashboard.Cities",
                        "detail_url": "http://localhost:8000/api/v1/pages/37/"
                    }
                },
            ]
        }
    ]
}

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

我在文档中找不到任何解决方案。我错过了什么吗?我想要这样的回应

            "related_cities": [
                {
                    "id": 28,
                    "name": "SomeCityName1",
                    "meta": {
                        "type": "dashboard.Cities",
                        "detail_url": "http://localhost:8000/api/v1/pages/28/"
                    }
                },
                {
                    "id": 37,
                    "name": "SomeCityName2",
                    "meta": {
                        "type": "dashboard.Cities",
                        "detail_url": "http://localhost:8000/api/v1/pages/37/"
                    }
                },
            ]
4

1 回答 1

1

无需覆盖 Wagtail 的 API 模块,就不可能添加名称。

但这是我们正在为 API 的第 2 版所做的工作(请参阅:https ://github.com/kaedroho/weps/blob/api-fields/draft/005-wagtail-api-fields.rst#nested-objects )。

于 2016-04-11T10:06:07.167 回答