查看有关OneToOne关系的SqlAlchemy文档.首先,您需要为每个模型提供主键.然后,您需要定义一个引用另一个模型的主键的外键.现在,您可以使用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))
现在您可以像这样访问您的模型:
request = Request.query.first() print(request.agent.name) agent = Agent.query.first() print(agent.request.applicationdate)