2013-10-31 106 views
1

我是新來的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!

+0

你可以顯示你正在運行的代碼實際添加用法嗎? –

回答

0

好吧,我需要爲MoonUsage添加主鍵列。下面的代碼現在可以運行...

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')