SQLAlchemy具有多个外键条目的多对多表

时间:2013-10-31 21:00:57

标签: python sqlalchemy

我是sqlalchemy的新手,我希望尽可能简单地做到这一点。我希望每月跟踪多家公司的域名使用情况,因此我设置了以下表格:

class Company(Base):
    __tablename__ = 'company'

    id = Column(Integer, primary_key = True)
    name = Column('name', String)


class Domains(Base):
    __tablename__ = 'domains'

    id = Column(Integer, primary_key=True)
    name = Column('name', String, unique=True)

class MonthlyUsage(Base):
    '''
    Track domain usage across all
    companies on a monthly basis.
    '''
    __tablename__ = 'monthlyusage'

    month = Column(DateTime)
    company_id = Column(Integer, ForeignKey('company.id'))
    domain_id  = Column(Integer, ForeignKey('domains.id'))

    # <...other columns snipped out...>

    company = relationship('Company', backref='company_assoc')
    domain = relationship('Domains', backref='domain_assoc')

这很好,直到我添加第二个月的使用情况详细信息。然后我得到重复的键值错误:

* sqlalchemy.exc.IntegrityError:(IntegrityError)重复键值违反了唯一约束“monthlyusage_pkey”*

这是否意味着我必须将“monthlyusage”分成第三个表格?这似乎不必要地复杂,因为所有需要唯一的是month,company_id和domain_id字段。

我的布局有什么建议,尽可能简单,但仍然正确吗?

TIA!

1 个答案:

答案 0 :(得分:0)

好的,我需要在MonthlyUsage中添加一个主键列。下面的代码现在有效......

class MonthlyUsage(Base):
    '''
    Track domain usage across all
    companies on a monthly basis.
    '''
    __tablename__ = 'monthlyusage'

    month = Column(DateTime)
    month_id = Column(Integer, primary_key=True)
    company_id = Column(Integer, ForeignKey('company.id'), primary_key=True)
    domain_id  = Column(Integer, ForeignKey('domains.id'), primary_key=True)

    # <...other columns snipped out...>

    company = relationship('Company', backref='company_assoc')
    domain = relationship('Domains', backref='domain_assoc')