Answer a question

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'

Answers

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 = db.Column(db.Integer, db.ForeignKey('request.id'))
    request = db.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)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐