如何在SQLAlchemy中指定外键列值?

ova*_*g25 4 python orm sqlalchemy exception foreign-keys

我的一个模型有以下关系:

class User(Base):
    account     = relationship("Account")
Run Code Online (Sandbox Code Playgroud)

我想手动设置帐户ID.

我的第一次尝试是这样的:

class User(Base):
    account     = relationship("Account")
    accounts_id = Column(Integer, ForeignKey("accounts.id"), nullable=True)

    @classmethod
    def from_json(cls, json):
        appointment = Appointment()
        appointment.account_id = json["account_id"]
        return appointment
Run Code Online (Sandbox Code Playgroud)

以上都不行.我们不能引用此列,因为SQLAlchemy会引发一个拟合.这是例外:

sqlalchemy.exc.InvalidRequestError: Implicitly combining column users.accounts_id with column users.accounts_id under attribute 'accounts_id'.  Please configure one or more attributes for these same-named columns explicitly.
Run Code Online (Sandbox Code Playgroud)

我试图通过文档进行搜索,并且通过多种方式获取属性但是我无法找到,更不用说设置它了.

  print(self.account.account_id)
  print(self.account.relationhip)
  print(self.account.properties)
  print(self.account.primaryjoin)
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

[编辑 - 上面添加的例外]

Pau*_*tte 6

使用Account该类定义relationship,并添加backref关键字参数:

from sqlalchemy.orm import relationship

class User(Base):

    accounts_id = Column(Integer, ForeignKey('account.id'))

class Account(Base):

    users = relationship('User', backref='account')
Run Code Online (Sandbox Code Playgroud)

backref关键字用于单个关系时,它与使用back_populates每个关系单独创建上述两个关系完全相同.

参考