Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

python - Flask SQLAlchemy Foreign Key Relationships

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'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...