[英]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. 我是sqlalchemy的新手,我想尽可能简单但正确地做到这一点。 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"* * sqlalchemy.exc.IntegrityError:(IntegrityError)重复键值违反了唯一约束“ 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.
这似乎不必要地复杂,因为唯一需要的是月份,company_id和domain_id字段。
Any suggestions for my layout here, to keep it as simple as possible, yet still correct? 对我的布局有什么建议,以使其尽可能简单但仍然正确?
TIA! TIA!
Ok, I needed to add a primary key column to MonthlyUsage. 好的,我需要向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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.