sqlalchemy同一选项卡的多个外键

2024-07-03 06:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个postgres数据库,看起来像这样:

      Table "public.entities"
    Column     |            Type             |                   Modifiers                    
---------------+-----------------------------+------------------------------------------------
 id            | bigint                      | not null default nextval('guid_seq'::regclass)
 type_id       | smallint                    | not null
 name          | character varying           | 
Indexes:
    "entities_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "entities_parent_id_fkey" FOREIGN KEY (parent_id) REFERENCES entities(id)
    "entities_type_id_fkey" FOREIGN KEY (type_id) REFERENCES entity_types(id)
Referenced by:
    TABLE "posts" CONSTRAINT "posts_id_fkey" FOREIGN KEY (id) REFERENCES entities(id)
    TABLE "posts" CONSTRAINT "posts_subject_1_fkey" FOREIGN KEY (subject_1) REFERENCES entities(id)
    TABLE "posts" CONSTRAINT "posts_subject_2_fkey" FOREIGN KEY (subject_2) REFERENCES entities(id)

    Table "public.posts"
  Column   |  Type  | Modifiers 
-----------+--------+-----------
 id        | bigint | not null
 poster_id | bigint | 
 subject_1 | bigint | not null 
 subject_2 | bigint | not null 
Indexes:
    "posts_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "posts_id_fkey" FOREIGN KEY (id) REFERENCES entities(id)
    "posts_poster_id_fkey" FOREIGN KEY (poster_id) REFERENCES users(id)
    "posts_subject_1_fkey" FOREIGN KEY (subject_1) REFERENCES entities(id)
    "posts_subject_2_fkey" FOREIGN KEY (subject_2) REFERENCES entities(id)

我正试图找出如何定义“posts”的orm对象来包含所有3个外键。注意,只有id是主键。其他的只是职位和实体之间的关系,而不是pk'd

class PostModel(EntitiesModel):
    __tablename__ = 'posts'

    id = db.Column(db.BigInteger, db.ForeignKey(EntitiesModel.id), primary_key=True, nullable=False)
    poster_id = db.Column(db.BigInteger, db.ForeignKey(UserModel.id), nullable=False)

    subject_1 = db.Column(db.BigInteger, db.ForeignKey(EntitiesModel.id), nullable=False)
    subject_2 = db.Column(db.BigInteger, db.ForeignKey(EntitiesModel.id), nullable=False)

我试过稍微修改一下,除了禁用subject_1上的外键之外,我似乎无法想出一个不会导致此错误的解决方案:

AmbiguousForeignKeysError: Can't determine join between 'entities' and 'posts'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.

有什么想法吗?


Tags: keyiddbnotcolumnnullpostssubject
1条回答
网友
1楼 · 发布于 2024-07-03 06:27:21

现在还不完全清楚到底是什么导致了这个问题,因为您省略了最重要的部分——引发该异常的代码,但是如果将关系属性添加到类PostModelthrows,该类尝试将外键参数添加到relationship调用,如下所示:

class PostModel(...):
    # ...
    subject1_id = Column(db.Column(db.BigInteger, db.ForeignKey(EntitiesModel.id), nullable=False)
    subject2_id = Column(db.Column(db.BigInteger, db.ForeignKey(EntitiesModel.id), nullable=False)
    subject1 = relationship(EntitiesModel, foreign_keys=subject1_id)
    subject2 = relationship(EntitiesModel, foreign_keys=subject2_id)

相关问题 更多 >