在SQLAlchemy中添加多个外键

时间:2016-05-05 16:02:25

标签: python

我正在遵循本指南 - http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html

这是我的代码

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.name, 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('users.id'))
  user = relationship("User", back_populates = 'addresses')
  def __repr__(self):
    return "<Address(email_address='%s')>" %self.email_address

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


Base.metadata.create_all(engine)

当我为User表创建记录时,我这样做:

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

要添加电子邮件地址,我这样做(按照指南):

candidate.addresses = [Address(email_address='jack_bean@gmail.com')]

我正试图弄清楚如何在事后添加多个电子邮件地址给杰克的记录。当我再试一次时

candidate.addresses = [Address(email_address='jack@gmail.com')]

它会删除地址表中jack_bean@gmail.com的外键(最初为1)并使其成为NULL

如何在创建初始记录后添加多个外键?

1 个答案:

答案 0 :(得分:0)

而不是:

candidate.addresses = [Address(email_address='jack_bean@gmail.com')]

如果您需要在候选人创建地址后添加地址,请执行以下操作:

candidate.addresses.append(Address(email_address="new@new.com"))
db_session.commit()