SQLAlchemy 关于外键和关联表的问题

SQLAlchemy problems with foreign keys and association tables

我正在尝试在个人、公司和该人在给定公司使用的电子邮件地址之间创建 link。

在 SQL 术语中,我认为这将是四个表,Person、Company、Email 和 email_company_association,在 email_company_association 中有两个 FK,一个用于电子邮件,一个用于公司。然后在电子邮件中发送一个 FK 给个人。电子邮件地址也可以直接连接到一个人,因此电子邮件中的人 FK。

然而我有点不知如何在 SQLAlchemy 中做到这一点。

我试过类似的东西:

class Person(Base):
    """
    A person
    """
    __tablename__ = 'persons'

    id = Column(Integer, Sequence('person_id_seq'), primary_key=True)
    name = Column(String(255), unique=True)
    surename = Column(String(255))
    forename = Column(String(255))

class Company(Base):
    """
    A company
    """
    __tablename__ = 'companies'

    id = Column(Integer, Sequence('company_id_seq'), primary_key=True)
    name = Column(String)
    email_addresses = relationship("Company_Email_Association", backref="company")
    person_id = Column(Integer, ForeignKey('persons.id'), nullable=False)
    person = relationship("Person", backref=backref('companies', order_by=id))

class Email(Base):
    """
    Email address
    """
    __tablename__ = 'emailaddresses'
    id = Column(Integer, primary_key=True)
    email = Column(String, nullable=False)
    person_id = Column(Integer, ForeignKey('persons.id'), nullable=False)
    person = relationship("Person", backref=backref('emailaddresses', order_by=id)) 

class Company_Email_Association(Base):
    __tablename__ = 'company_email_assoc'
    company_id = Column(Integer, ForeignKey('companies.id'), primary_key=True)
    email_id = Column(Integer, ForeignKey('emailaddresses.id'), primary_key=True)
    email = relationship("Email")

我正在使用这个ca。像这样:

p = Person()
c = Company(name="Foo LTD")
cea = Company_Email_Association()
cea.email = Email(email="foo@example.org") # This breaks since Email needs persons.id
c.email_addresses.append(cea)
p.companies.append(c)

这是我得到的错误:

sqlalchemy.exc.IntegrityError: (IntegrityError) null value in column "person_id" violates not-null constraint
DETAIL:  Failing row contains (1, foo@example.org, null).
 'INSERT INTO emailaddresses (email, person_id) VALUES (%(email)s, %(person_id)s) RETURNING emailaddresses.id' {'person_id': None,'email': 'foo@example.org'}

我猜我做的 SQLAlchemy 和建模都非常错误,但我不知道该怎么做。

似乎模型和数据库 类 是正确的,但我对它们的使用却不正确。使用以下代码似乎可以满足我的要求。

p = Person()
c = Company(name="Foo LTD")
cea = Company_Email_Association()
cea.email = Email(email="foo@example.org") # This breaks since Email needs persons.id
p.emailaddresses.append(cea.email)
c.email_addresses.append(cea)
p.companies.append(c)

将电子邮件地址添加到 Person 对象至关重要。