[英]Flask SQLAlchemy Foreign Key Relationships
I'm having a lot of trouble getting my head around foreign keys and relationships in SQLAlchemy.我在处理 SQLAlchemy 中的外键和关系时遇到了很多麻烦。 I have two tables in my database.
我的数据库中有两个表。 The first one is
Request
and the second one is Agent
.第一个是
Request
,第二个是Agent
。 Each Request
contains one Agent
and each Agent
has one Request
.每个
Request
包含一个Agent
,每个Agent
有一个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))
When I am running db.create_all()
I get the following error当我运行
db.create_all()
出现以下错误
Could not initialize target column for ForeignKey 'request.agent' on table 'applicant': table 'request' has no column named 'agent'
无法为表 'applicant' 上的 ForeignKey 'request.agent' 初始化目标列:表 'request' 没有名为 'agent' 的列
Have a look at the SqlAlchemy documentation on OneToOne relationships .查看有关 OneToOne 关系的SqlAlchemy 文档。 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.
现在,您可以使用允许直接访问相关模型的 backref 定义关系。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.