How to specify a foreign key column value in SQLAlchemy?

One of my models has the following ratio:

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

I would like to set the account ID manually.

My first attempt:

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 work does not work. We cannot reference this column because SQLAlchemy throws a fit. This is an 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 tried to hunt through documents and experimented in order to get a lot of attributes, but I could not find them, and even less to set them.

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

Any ideas?

[Excluded by editing]

+4
source share
1 answer

Use the class Accountto define relationshipand add a keyword argument 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 .

+6

All Articles