【问题标题】:How do you specify the foreign key column value in SQLAlchemy?如何在 SQLAlchemy 中指定外键列值?
【发布时间】:2015-09-04 11:23:48
【问题描述】:

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

class User(Base):
    account     = relationship("Account")

我想手动设置帐号。

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

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

上述方法不起作用。我们不能参考这个专栏,因为 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.

我尝试通过文档搜索并尝试通过多种方式获取属性,但我无法找到,更不用说设置它了。

  print(self.account.account_id)
  print(self.account.relationhip)
  print(self.account.properties)
  print(self.account.primaryjoin)

有什么想法吗?

[编辑-在上面添加异常]

【问题讨论】:

  • 你的类方法有点不连贯。 self 应该来自哪里?您是否省略了self = cls()
  • @SingleNegationElimination - 修复它以反映我实际拥有的东西
  • 该声明会发生什么,您预计会发生什么?
  • 你怎么打电话给User.from_json()?您有任何要处理的数据吗?
  • @SingleNegationElimination - 是的,我传递给它一个 JSON 字典。我在上面添加了一个例外以更准确地反映问题。我的自定义构造函数运行良好,但由于来自 ORM 的InvalidRequestError 无法设置属性

标签: python exception orm sqlalchemy foreign-keys


【解决方案1】:

使用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')

backref 关键字用于单个关系时,与上述两个关系分别使用back_populates 创建完全一样。

参考文献

【讨论】:

    猜你喜欢
    • 2015-01-16
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多