1

我是 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”拆分为第三张表?这似乎不必要地复杂,因为需要唯一的只是月份、company_id 和 domain_id 字段。

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

蒂亚!

4

1 回答 1

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')
于 2013-11-01T14:05:07.837 回答