![](/img/trans.png)
[英]sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidForeignKey) there is no unique constraint matching given keys for referenced table "dicom"
[英]Python - sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidForeignKey) there is no unique constraint matching given keys for referenced table
我是 Sqlalchemy 的新手。 我有 2 個對象 User 和 Product。 我想在他們之間建立關系。
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)
但我收到錯誤sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidForeignKey) there is no unique constraint matching given keys for referenced table "user".
如果我刪除關系,它會起作用,但這不是我的目的。 我該如何解決? 我想問一下為什么要使用關系?
您沒有將user
與product
連接起來的列,因此 sqlalchemy 無法解析這種關系。 relationship
是一個幫助器,可以幫助您提供/接收給定類型的對象,而不僅僅是鍵值。
您仍然需要擁有連接可用表的實際列,例如Product
上的user_id
或User
上的product_id
,以便該relationship
能夠找出User
和Product
的連接方式。
由於您的username
名列連接到agent
表而不是user
表,SQLAlchemy 無法使用該列來鏈接兩個表。 添加一個單獨的user_username
(或者更好的是,使用設置了primary_key=True
的實際自動遞增id
,以便您獲得每個用戶和產品的唯一 id)字段以及鏈接到用戶表的外鍵,或者將您當前的外鍵更改為鏈接到user
而不是agent
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.