当前位置: 动力学知识库 > 问答 > 编程问答 >

flask - Retrieve arbitrary PK from db model

问题描述:

If I have a model with PK, lets say device_id (so it's not id) which I relate in another table:

x = db.Column(db.Integer, db.ForeignKey('device.device_id'))

How can I reference this column in sqlalchemy query?

In Django I could use Device.pk and it would resolve the PK. Is this possible in flask with sqlalchemy?

网友答案:

You can either join it, or use a relationship for SQLAlchemy to work it's magic automatically.

It looks like you're talking about a Many to One relationship, so, using the documentation example:

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    addresses = db.relationship('Address', backref='person',
                                lazy='dynamic')

class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50))
    person_id = db.Column(db.Integer, db.ForeignKey('person.id'))

If the PK was named differently on the Person, you would just adjust the ForeignKey to match:

class Person(db.Model):
    toot = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    addresses = db.relationship('Address', backref='person',
                                lazy='dynamic')

class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50))
    person_id = db.Column(db.Integer, db.ForeignKey('person.toot'))

If I then wanted to find out all Person objects who have an email address of [email protected] I could just say:

Person.query.join(Address).filter(Address.email='[email protected]').all()
分享给朋友:
您可能感兴趣的文章:
随机阅读: