简体   繁体   English

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

[英]How do you specify the foreign key column value in SQLAlchemy?

One of my models has the following relationship: 我的一个模型有以下关系:

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

I would like to set the account id manually. 我想手动设置帐户ID。

My first attempt was this: 我的第一次尝试是这样的:

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

The above dosen't work. 以上都不行。 We can't refer to this column because SQLAlchemy throws a fit. 我们不能引用此列,因为SQLAlchemy会引发一个拟合。 This is the exception: 这是例外:

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.

I've tried hunting through the docs and expermiented with getting to the attribute numerous ways but I haven't been able to find, much less set it. 我试图通过文档进行搜索,并且通过多种方式获取属性但是我无法找到,更不用说设置它了。

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

Any ideas? 有任何想法吗?

[Edit- added exception above] [编辑 - 上面添加的例外]

Use the Account class to define the relationship , and add the backref keyword argument: 使用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')

When the backref keyword is used on a single relationship, it's exactly the same as if the above two relationships were created individually using back_populates on each. backref关键字用于单个关系时,它与使用back_populates上的back_populates单独创建上述两个关系back_populates

References 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM