简体   繁体   中英

Python - sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidForeignKey) there is no unique constraint matching given keys for referenced table

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?

You have no column that connects user with product , so sqlalchemy has no way of resolving the relationship. relationship is a helper that helps you with providing/receiving objects of the given type instead of just the key value.

You still need to have the actual column that connects the tables available, such as either user_id on Product or product_id on User , so that relationship is able to find out how User and Product is connected.

Since your username column is connected to an agent table and not a user table, SQLAlchemy has no way to use that column to link the two tables. Either add a separate user_username (or better yet, use an actual autoincrementing id with primary_key=True set, so that you get unique ids for each User and Product) field with a ForeignKey that links to the user table, or change your current ForeignKey to link to user instead of agent .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM