我需要获取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}
答案 0 :(得分:3)
在Plane类中添加一对多关系,如下所示。 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/
我为一篇帖子写了类似的代码到很多评论: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