Flask SQLAlchemy Foreign Key Relationships

陌路散爱 提交于 2021-02-16 04:42:16

问题


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))

When I am running db.create_all() I get the following error

Could not initialize target column for ForeignKey 'request.agent' on table 'applicant': table 'request' has no column named 'agent'


回答1:


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)


来源:https://stackoverflow.com/questions/41569206/flask-sqlalchemy-foreign-key-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!