【发布时间】:2018-10-01 03:06:35
【问题描述】:
我正在尝试显示由外键链接的另一个表中的医生名字。我可以显示医生 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)
【问题讨论】:
-
如果可以打印result.data,它会显示什么?
-
我可以打印 result.data 但我只能打印该表中的数据。尝试打印
a.doctor_id.first_name不会打印任何内容。 -
根据您提到的参考问题,您是否尝试过在Doctor Object中使用这样的约会= db.relationship(Appointment, backref ='doctor')。
-
当我的 html 是
{{ a.doctor.first_name }}并且我的查询是all_appmts =db.session.query(Appointment).filter_by(patient_id=id).join(Doctor).all()时,我收到此错误jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'doctor' -
define __tablename__ = 'doctor' for Doctor 课程,同样的方式用于预约课程。
标签: python sqlalchemy jinja2