通读sql炼金术Jinj

2024-04-28 05:12:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试显示另一个由外键链接的表中的名字。我可以显示医生的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)

Tags: idfalsetruedbcolumnintegerallclass
1条回答
网友
1楼 · 发布于 2024-04-28 05:12:58

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

{
 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())

然后保持jinja模板不变

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

会有用的

相关问题 更多 >