I\'m trying to add an item to my database with SQLAlchemy + Python, but keep getting an error.
My database_setup.py:
class company(Base):
__table
First of all, when defining a class in Python, it is of good practice to to start the names with an uppercase letter like this:
class Company(Base):
__tablename__ = 'company'
compID = Column(Integer, primary_key = True)
name = Column(String(80), nullable = False)
class Item(Base):
__tablename__ = 'items'
itemID = Column(Integer, primary_key = True)
name = Column(String(80), nullable = False)
category = Column(String(250))
description = Column(String(250))
price = Column(String(8))
compID = Column(Integer, ForeignKey('company.compID'))
company = relationship(company)
That being said, it is not why your code throws an error. :)
The Item
constructor expects an instance of the object Company
to by passed as a value of the variable company
Here the answer of @alecxe is valid.
You should replace your code with:
JawboneUP3 = Item(itemID="1",
name="Jawbone UP3",
description="The latest UP!",
category="tracker",
price="$174.99",
company=company(name="Jawbone"))
Adding this object to the session and comiting the changes will actually make two entries to your database:
Here you should fetch the company Jawbone from your table "company" and pass it as an argument to the Item
constructor, like this:
jawbone = session.query(Company).filter_by(name="Jawbone").first()
JawboneUP3 = Item(itemID="1",
name="Jawbone UP3",
description="The latest UP!",
category="tracker",
price="$174.99",
company=jawbone)
For the session
part check this