我有一家公司,其中包含国家/地区代码、企业 ID 和员工列表:
class Company(db.Model):
id = db.Column(db.Integer, primary_key=True)
business_id = db.Column(db.String(20), nullable=False)
country_code = db.Column(db.String(2), nullable=False)
employee = db.relationship('Employee', backref='company')
class Employee(db.Model):
id = db.Column(db.Integer, primary_key=True)
company_id = db.Column(db.Integer, db.ForeignKey('company.id'))
但是假设数据不断变化,并且同一家公司的 id
并不总是相同(公司可能会从数据库中删除,然后使用不同的 重新添加) >id
)。但是,country_code
和 business_id
的组合始终保证对于同一家公司来说是唯一的且恒定的。
如何为 Employee
创建两个指向 Company
的 country_code
和 business_id
的外键?
我尝试通过一个较旧的 StackOverflow 问题来执行此操作,但它引发了不应使用 'str'
的错误:
class Company(db.Model):
id = db.Column(db.Integer, primary_key=True)
business_id = db.Column(db.String(20), nullable=False)
country_code = db.Column(db.String(2), nullable=False)
employee = db.relationship('Employee', backref='company', foreign_keys=['Company.business_id', 'Company.country_code'])
但是,Python 的语法阻止我引用类本身。
最佳答案
我不确定您到底在问什么,但下面的代码示例做了两件事,我认为这会有所帮助:
- 定义复合外键
- 指示
Company
和Employee
之间的关系使用哪个外键
型号:
class Company(db.Model):
id = db.Column(db.Integer, primary_key=True)
business_id = db.Column(db.String(20), nullable=False)
country_code = db.Column(db.String(2), nullable=False)
name = db.Column(db.String(), nullable=False)
employee = db.relationship(
'Employee', backref='company',
# 2. indicate FK to use below
foreign_keys=lambda: [Employee.business_id, Employee.country_code],
# foreign_keys=lambda: Employee.company_id,
)
class Employee(db.Model):
id = db.Column(db.Integer, primary_key=True)
company_id = db.Column(db.ForeignKey('company.id'))
name = db.Column(db.String(), nullable=False)
business_id = db.Column(db.String(20), nullable=False)
country_code = db.Column(db.String(2), nullable=False)
# 1. define a composite foreign key
__table_args__ = (
db.ForeignKeyConstraint(
['business_id', 'country_code'],
['company.business_id', 'company.country_code']
),
)
关于python - child 有多个外键给 parent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929947/