Flask SQLAlchemy 外键关系 [英] Flask SQLAlchemy Foreign Key Relationships
问题描述
我在处理 SQLAlchemy 中的外键和关系时遇到了很多麻烦.我的数据库中有两个表.第一个是Request
,第二个是Agent
.每个Request
包含一个Agent
,每个Agent
有一个Request
.
I'm having a lot of trouble getting my head around foreign keys and relationships in SQLAlchemy. I have two tables in my database. The first one is Request
and the second one is Agent
. Each Request
contains one Agent
and each Agent
has one Request
.
class Request(db.Model):
__tablename__ = 'request'
reference = db.Column(db.String(10), primary_key=True)
applicationdate = db.Column(db.DateTime)
agent = db.ForeignKey('request.agent'),
class Agent(db.Model):
__tablename__ = 'agent'
id = db.relationship('Agent', backref='request', \
lazy='select')
name = db.Column(db.String(80))
company = db.Column(db.String(80))
address = db.Column(db.String(180))
当我运行 db.create_all()
时出现以下错误
When I am running db.create_all()
I get the following error
无法为表 'applicant' 上的 ForeignKey 'request.agent' 初始化目标列:表 'request' 没有名为 'agent' 的列
Could not initialize target column for ForeignKey 'request.agent' on table 'applicant': table 'request' has no column named 'agent'
推荐答案
查看 关于 OneToOne 关系的 SqlAlchemy 文档.首先,您需要为每个模型提供一个主键.然后你需要定义一个外键,它引用另一个模型的主键.现在,您可以使用允许直接访问相关模型的 backref 定义关系.
Have a look at the SqlAlchemy documentation on OneToOne relationships. First you need to supply a primary key for each Model. Then you need to define one foreign key which refers to the Primary Key of the other model. Now you can define a relationship with a backref that allows direct access to the related model.
class Request(db.Model):
__tablename__ = 'request'
id = db.Column(db.Integer, primary_key=True)
applicationdate = db.Column(db.DateTime)
class Agent(db.Model):
__tablename__ = 'agent'
id = db.Column(db.Integer, primary_key=True)
request_id = Column(Integer, ForeignKey('request.id'))
request = relationship("Request", backref=backref("request", uselist=False))
name = db.Column(db.String(80))
company = db.Column(db.String(80))
address = db.Column(db.String(180))
现在您可以像这样访问您的模型:
Now you can access your models like this:
request = Request.query.first()
print(request.agent.name)
agent = Agent.query.first()
print(agent.request.applicationdate)
这篇关于Flask SQLAlchemy 外键关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!