I'm newbie in Sqlalchemy. I have 2 objects User and Product. I want to create relationship between them.
from sqlalchemy import Column, String, Boolean, create_engine, ForeignKey, PrimaryKeyConstraint
from sqlalchemy.orm import relationship
class User():
__tablename__ = 'user'
username= Column(String, primary_key = True)
random_string = Column(String)
class Product():
__tablename__ = 'product'
username= Column(String, ForeignKey('user.username'))
productname = Column(String)
status = Column(Boolean)
usr = relationship("User", back_populates="product")
Base.metadata.create_all(engine)
But I get the error sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidForeignKey) there is no unique constraint matching given keys for referenced table "user".
If I remove relationship, it works but this is not my purpose. How can I fix it? And I want to ask why we should use relationship?