我试图通过使用来自另一个表“ Nutritional Values”的数据来设置表的foreign_key列
class NutritionalValues(db.Model):
__tablename__ = 'nutritionalvalues'
id = db.Column(db.Integer, primary_key=True)
item = db.Column(db.String(200), nullable=False)
calories = db.Column(db.Float, nullable=False)
totalfat = db.Column(db.Float, nullable=False)
使用
consumed_nutrionalvalue_id = NutritionalValues.query.filter_by(item=consumed_item).id
其中“ consumed_item”是一些与NutritionalValues表的一行的“ item”值的字符串完全匹配的字符串
但是我得到了错误
AttributeError: 'BaseQuery' object has no attribute 'id'
Traceback (most recent call last)
File "/Users/benjamattesjaroen/helloPython/env/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/benjamattesjaroen/helloPython/env/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "/Users/benjamattesjaroen/helloPython/env/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/benjamattesjaroen/helloPython/env/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/benjamattesjaroen/helloPython/env/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/Users/benjamattesjaroen/helloPython/env/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/benjamattesjaroen/helloPython/env/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/benjamattesjaroen/helloPython/env/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/benjamattesjaroen/helloPython/env/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/benjamattesjaroen/helloPython/env/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/benjamattesjaroen/helloPython/app.py", line 65, in index
consumed_nutrionalvalue_id = NutritionalValues.query.filter_by(item=consumed_item).id
AttributeError: 'BaseQuery' object has no attribute 'id'
但是很清楚“营养价值”是否有一个名为“ id”的列?如何为查询访问存储在表的该列中的整数?
答案 0 :(得分:1)
以下是查询
NutritionalValues.query.filter_by(item=consumed_item)
要获取对象(此o in orm),可以使用.first()
或许多结果.all()
NutritionalValues.query.filter_by(item=consumed_item).first()
您现在有了一个普通对象,您可以执行pythonic方法来进行成员访问。
这很有趣,因为您可以在执行获取结果的执行之前构建动态查询。