SQLAlchemy外键和关联表的问题

时间:2015-02-09 21:14:08

标签: python sql sqlalchemy

我正在尝试在个人,公司和该人在指定公司使用的电子邮件地址之间创建链接。

在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和建模都非常错误,但我不知道该做什么。

1 个答案:

答案 0 :(得分:1)

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

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对象至关重要。