Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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. 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]

like image 424
ovatsug25 Avatar asked Jun 18 '15 17:06

ovatsug25


People also ask

What is a foreign key in SQL?

A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table. ... The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.

What is foreignkeyconstraintand Index in SQL alchemy?

In SQLAlchemy the key classes include ForeignKeyConstraintand Index. Defining Foreign Keys¶ A foreign keyin SQL is a table-level construct that constrains one or more columns in that table to only allow values that are present in a different set of columns, typically but not always located on a different table.

How do I add a foreign key to an existing table?

SQL FOREIGN KEY on ALTER TABLE. To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already created, use the following SQL: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Orders. ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

What is the difference between the primary key and foreign key columns?

The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table. The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the parent table.


1 Answers

Use the Account class to define the relationship, and add the backref keyword argument:

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.

References

  • Linking Relationships with Backref

  • Controlling Cascade on Backrefs

  • SQLAlchemy ORM Examples

like image 89
Paul Sweatte Avatar answered Nov 14 '22 23:11

Paul Sweatte