Open tobi-or-not opened 2 months ago
It would seem to me to be pretty normal but I may be mistaken.
You're sending hour
attribute to your WaterLevelSchema
when it's expecting time
.
The syntax for alias is good, but in this case you don't want an alias, you just want a different schema.
So you remove hour
from WaterLevelSchema
, you define time
as time: datetime
(not an alias), and you annotate your object to output time
instead of hour
.
Btw I don't think you need to return DashboardSchema
, as it's defined in response=DashboardSchema
, that's the whole point, you can return the object as-is, as long as it's in the format you defined.
class WaterLevelSchema(Schema):
time: datetime
# (...)
@router.get('/dashboard/{location_id}', response=DashboardSchema)
def dashboard(request, location_id):
latest_water_levels = (
# (...)
.annotate(day=TruncDay('created_at'), time=TruncHour('created_at')) # Truncate timestamp to day and hour
# (...)
)
return {
# (...)
historic_water_levels_m3=latest_water_levels
}
Thanks @lapinvert!
Upon review, the name change works. I am still confused, though, why I hour
is accessible as a 'regular' schema field but not via an alias.
The reason I am returning the DashboardSchema is that the data for it comes from a number of different queries. I guess I could
response=DashboardSchema
from the decorator to avoid duplication orresponse=DashboardSchema
and return a dict instead.Thanks for your thoughts!
I have an ORM query that creates annotations. While
hour
makes sense within the context of the query, as a property in the API response, I'd like to call the fieldtime
. In theWaterLevelSchema
, I can specifyhour: datetime
, which works but if I only specifytime: datetime = Field(..., alias='hour')
I get an error:How can I create an alias for a field that was created via annotation in a Django ORM query? When I specify both
hour
andtime
in theWaterLevelSchema
, there is no error, but then I have both properties in the API response, which I do not want. Do I have my thinking backwards? How can this be done?