问题
I have the following two classes in my app.models and i'm using the wagtail APIs to get the data as 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)
So, when I try /api/v1/pages/?type=dashboard.States&fields=name,related_cities, it returns the following data:
{
"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/"
}
},
]
}
]
}
In the related_cities field, it returns id
and meta
of the cities. How can I get the name of the city in the response here, without making an extra query? :/
I couldn't find any solution in the Documentation. Am I missing something? I want the response something like this
"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/"
}
},
]
回答1:
Adding the name there isn't possible without having to override bits of Wagtail's API module.
But this is something we are working on for version 2 of the API (see: https://github.com/kaedroho/weps/blob/api-fields/draft/005-wagtail-api-fields.rst#nested-objects).
来源:https://stackoverflow.com/questions/36498417/how-to-access-manytooneforeignkey-data-without-making-extra-queries-in-wagtaild