I'm trying to set the foreign_key column of the table by using data from another table 'Nutritional Values'
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)
by using
consumed_nutrionalvalue_id = NutritionalValues.query.filter_by(item=consumed_item).id
where 'consumed_item' is some string that exactly matches the string of the 'item' value for one row of the NutritionalValues table
but I get the error
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'
but cleary 'Nutritional Values' does have a column called 'id'? How can I access the integer stored in that column of the table for my query?
NutritionalValues.query.filter_by(item=consumed_item)is a query. You need to use.first()to get the object.some_query.first().idshould work, I've just tested similar code.