问题描述
我有一个Location
模型和一个Weather
模型。每个Location
对象都有多个Weather
对象(一对多关系)。
class Weather(db.Model):
id = db.Column(db.Integer,primary_key=True)
date = db.Column(db.DateTime,nullable=False)
_temperature = db.Column(db.String(500),nullable=False)
lat = db.Column(db.Float,nullable=False)
lon = db.Column(db.Float,nullable=False)
location = db.relationship('Location',backref=db.backref('weathers',lazy=True))
__table_args__= (
db.ForeignKeyConstraint(['lat','lon'],['location.lat','location.lon']),)
def add_temperature(self,temperature):
if not self._temperature:
self._temperature = temperature
else:
self._temperature = self._temperature + ';' + temperature
def get_temperature(self):
return self._temperature.split(';')
_temperature
对象中的Weather
字段存储多个以;作为字符串:
37.7;37.1;36.7;36.3;36.0;35.6;35.2;35.1;35.9;38.1;40.3;42.4;43.8;44.9;45.6;45.7;44.9;43.0;41.7;40.7;39.8;39.1;38.4;37.9
我想整理位置对象,以便对特定位置的GET调用的响应返回Weather
对象的数组:
[
{
"id": 1,"date": "1985-01-01","location": {
"lat": 36.1189,"lon": -86.6892,"city": "Nashville","state": "Tennessee"
},"temperature": [
37.3,36.8,36.4,...
]
},...
]
我尝试像这样定义marshal_with
字段:
resource_fields = {
'id': fields.Integer,'date': fields.DateTime('iso8601'),'temperature': fields.List(fields.nested(fields.Float,attribute='get_temperature')),'location': fields.nested(location_details)
}
但是我得到了"temperature":null
的回复。有什么方法可以在编组字段中调用Weather.get_temperature
函数?我的资源定义为:
class WeatherList(Resource):
@marshal_with(resource_fields)
def get(self):
args = WeatherGetParser().parse_args()
result = Weather.query.filter_by(lat=args['lat'],lon=args['lon']).all()
return result
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)