简体   繁体   中英

SQLAlchemy Many-to-many table with multiple foreign key entires

I'm new with sqlalchemy and I want to do this as simply as possible, yet correctly. I want to track domain use across multiple companies on a monthly basis, so I set up the following tables:

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

This works fine, until I add usage details for the second month. Then I get duplicate key value errors:

*sqlalchemy.exc.IntegrityError: (IntegrityError) duplicate key value violates unique constraint "monthlyusage_pkey"*

Does this mean I have to split out the "monthlyusage" into a third table? That seems unnecessarily complicated, since all that needs to be unique is the month, company_id, and domain_id fields.

Any suggestions for my layout here, to keep it as simple as possible, yet still correct?

TIA!

Ok, I needed to add a primary key column to MonthlyUsage. The code below now works...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM