创建PostgreSQL数据库遇外键约束匹配错误,求排查修复方案
错误原因
你定义的shop_item_skus表使用了复合主键(id和sku_internal_identifier同时标记为primary_key=True),这意味着PostgreSQL仅会保证这两个字段的组合是唯一的,单独的id字段并没有自动获得唯一约束。而shop_sku_prices表中的sku_id外键仅关联shop_item_skus.id,但PostgreSQL要求外键必须关联到被引用表的唯一约束(主键或唯一索引),因此触发了这个错误。
解决方法
有两种可行的修复方案,根据业务需求选择:
方案1:让shop_item_skus.id成为唯一主键
如果业务逻辑中id本身应该是全局唯一的,只需将sku_internal_identifier的primary_key=True去掉,改为普通字段或添加唯一约束:
__tablename__ = "shop_item_skus" id = Column( Integer, autoincrement=True, primary_key=True ) sku_internal_identifier = Column( String(32), nullable=False, unique=True ) # 改为唯一约束 name = Column( String(128), nullable=False ) description = Column( String(256), nullable=False ) category = Column( String(32) ) purchaseable = Column( Boolean, nullable=False, default=False ) soft_currency_cost = Column( Integer ) hard_currency_cost = Column( Integer ) steam_sellable = Column( Boolean, default=False ) # 修复重复的default参数
方案2:外键关联复合主键的全部字段
如果业务上确实需要id和sku_internal_identifier作为复合主键,那么shop_sku_prices需要同时引用这两个字段作为外键:
__tablename__ = "shop_sku_prices" id = Column( Integer, autoincrement=True, primary_key=True ) sku_id = Column( Integer, nullable=False, primary_key=True ) sku_internal_identifier = Column( String(32), nullable=False ) # 定义复合外键约束 __table_args__ = ( ForeignKeyConstraint( [sku_id, sku_internal_identifier], ["shop_item_skus.id", "shop_item_skus.sku_internal_identifier"] ), ) currency = Column( String(5), nullable=False ) unit_price = Column( Integer, nullable=False ) def __init__(self, sku_id, sku_internal_identifier, currency, unit_price): self.sku_id = sku_id self.sku_internal_identifier = sku_internal_identifier self.currency = currency self.unit_price = unit_price
内容的提问来源于stack exchange,提问作者zille
相关产品推荐
相关产品推荐

