SQLAlchemy 一对多查询输出

SQLAlchemy one to many query output

我需要获取 planes 及其所有对应 bookings 的列表,理想情况下是有一个飞机列表,其中每个飞机都有一个预订列表作为其属性之一,因此它可以很容易 json 编码。我如何使用 SQLAlchemy 执行此操作?我怀疑 SQLAlchemy 有一些强大的功能可以使这变得简单,我宁愿不必执行 2 个查询并处理结果。

例如结果:

Plane
- id:       -- 1
- name:     -- Eagle Bravo
- bookings: -- Booking1, Booking2, Booking3

Plane
- id:       -- 2
- name:     -- Charlie Bravo
- bookings: -- Booking4, Booking5, Booking6

Plane
- id:       -- 3
- name:     -- Alpha Bravo
- bookings: -- Booking7, Booking8, Booking9

飞机和预订模型:

class Booking(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    start_date = db.Column(db.DateTime)
    end_date = db.Column(db.DateTime)
    person_id = db.Column(db.Integer, db.ForeignKey('person.id'))
    person = db.relationship('Person', backref=db.backref('Bookings', lazy='dynamic'))
    plane_id = db.Column(db.Integer, db.ForeignKey('plane.id'))

    def __init__(self, start_date, end_date, person_id):
        self.start_date = start_date
        self.end_date = end_date
        self.person_id = person_id

    def __repr__(self):
        return '<Booking... %r>'

    def as_dict(self):
       return {c.name: getattr(self, c.name) for c in self.__table__.columns}


class Plane(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Plane... %r>'

    def as_dict(self):
       return {c.name: getattr(self, c.name) for c in self.__table__.columns}

在您的平面 class 中添加一对多关系,如下所示。 models.py

class Plane(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    bookings=db.relationship('Bookings', backref='plane', lazy='dynamic')

然后您可以通过将飞机变量传递给您的视图来获取所有飞机预订,如下所示

controller.py

@app.route('/list')
def plane_list():
    planes=Plane.query.all()
    return render_template('index.html', planes=planes)

Views.py

{% for plane in planes %}
  {{plane.id}]
  {{plane.name}}
  {%for booking in plane.bookings.all()%}
       {{booking.id}},       

   {%endfor%}
{%endfor%}

记录在此处:http://techarena51.com/index.php/one-to-many-relationships-with-flask-sqlalchemy/

我为一个 post 写了类似的代码给许多评论:https://github.com/Leo-g/flask-blog/blob/master/app/templates/single.html https://github.com/Leo-g/flask-blog/blob/master/app/models.py