我正在尝试显示另一个由外键链接的表中的名字。我可以显示医生的id,但不能显示他的名字。你知道吗
我看了这个解决方案 reading from joined query in flask-sqlalchemy 但是它有点不同,因为我是从另一边查询,不能使用backref值作为参考。我已经删除了不相关的代码。你知道吗
class Appointment(db.Model):
id = db.Column(db.Integer, primary_key=True)
patient_id = db.Column(db.Integer, db.ForeignKey('patient.id'),
nullable=False)
doctor_id = db.Column(db.Integer, db.ForeignKey('doctor.id'),
nullable=False)
class Doctor(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(30), unique=False, nullable=False)
appointments = db.relationship('Appointment', backref =
db.backref('doctor',lazy=True))
以及查询
all_appmts = db.session.query(Appointment)
.filter_by(patient_id=id)
.join(Doctor)
result =appointments_schema.dump(all_appmts)
return render_template('patient.html', all_appointments=result.data)
这就是我试过的
{% for a in all_appointments %}
<td>{{ a.doctor_id.first_name }}</td>
{% endfor %}
显示的医生姓名应基于该预约的医生id。你知道吗
这是棉花糖的部分。你知道吗
class AppointmentSchema(ma.Schema):
class Meta:
# Fields to expose
fields = ('id','start_datetime', 'end_datetime', 'title',
'patient_id', 'doctor_id')
appointments_schema = AppointmentSchema(many=True)
您正在尝试访问
doctor_id.first_name
。但是关系的名称是doctor
。如果要将查询结果转换为dict列表,那么还应该序列化appointment.doctor
关系,使dict看起来像然后你可以这样访问它
但是如果您只是计划在jinja模板中使用它,那么需要序列化这些对象吗?相反,您可以将
query.all()
的结果传递给模板。Jinja可以直接访问python对象并显示数据。因此,与其result =appointments_schema.dump(all_appmts)
,不如这样做然后保持jinja模板不变
会有用的
相关问题 更多 >
编程相关推荐