Morgan Allen Morgan Allen - 5 months ago 21x
Python Question

Adding in multiple foreign keys in SQLAlchemy

I'm following this guide -

Here is my code

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship

engine = create_engine('sqlite:///test.db', echo=True)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()

class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (, self.fullname, self.password)

class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key = True)
email_address = Column(String, nullable=False)
user_id = Column(Integer, ForeignKey(''))
user = relationship("User", back_populates = 'addresses')
def __repr__(self):
return "<Address(email_address='%s')>" %self.email_address

User.addresses = relationship ("Address",, back_populates="user")


When I create a record for the
table, I do it like this:

candidate = User(name='Jack', fullname='Jack Bean', password='blah')

And to add in email addresses, I do it like this (following the guide):

candidate.addresses = [Address(email_address='')]

I'm trying to figure out how to add multiple email address to Jack's record after the fact. When I try it again

candidate.addresses = [Address(email_address='')]

It erases the foreign key for
in the Address table (it initially was 1) and makes it

How do I add multiple foreign keys after creating the initial record?


Instead of doing:

candidate.addresses = [Address(email_address='')]

if you need to add an address to a candidate after they have already been created, do this: