【问题标题】:Reading through joined query Sqlalchemy Jinja阅读连接查询 Sqlalchemy Jinja
【发布时间】: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


【解决方案1】:

您正在尝试访问doctor_id.first_name。但是关系的名称是doctor。如果要将查询结果转换为字典列表,则还应序列化 appointment.doctor 关系,以便字典看起来像

{
 id: 12,
 doctor: {
  id: 34
 }
}

那你就可以这样访问了

 <td>{{ a.doctor.first_name }}</td>

但是如果你只是打算在 jinja 模板中使用它,那么序列化对象有什么需要呢?相反,您可以将 query.all() 的结果传递给模板。 Jinja 可以直接访问 python 对象并显示数据。所以不要result =appointments_schema.dump(all_appmts),尝试这样做

all_appmts = db.session.query(Appointment)
.filter_by(patient_id=id)
.join(Doctor)
return render_template('patient.html', all_appointments=all_aptmts.all())

然后保持神社模板不变

 {% for a in all_appointments %}
 <td>{{ a.doctor.first_name }}</td>
 {% endfor %}

会有用的

【讨论】:

  • 在最后一个代码块中,您仍然有来自 OP 示例的不正确的 a.doctor_id.first_name ;)
  • 非常感谢!有用。你还帮助我更好地理解了棉花糖,我现在明白为什么它不起作用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 1970-01-01
  • 2017-05-29
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多