gpt4 book ai didi

mysql - 如何在flask sqlalchemy中选择列

转载 作者:行者123 更新时间:2023-11-29 21:34:43 27 4
gpt4 key购买 nike

如何从另一个表中选择名称列而不是 id ,示例:

class Attendance(db.Model):
__tablename__ = 'zk_attendance'
id = db.Column(db.Integer,primary_key=True)
uid = db.Column(db.Integer,db.ForeignKey('zk_users.uid'))
date = db.Column(db.Date)
time = db.Column(db.Time)
device = db.Column(db.Integer,db.ForeignKey('devices.id'))
user = db.relationship('Users',backref=db.backref('user', lazy='dynamic'))



class Users(db.Model):
__tablename__ = 'zk_users'
uid = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String)

如果我想选择所有出席者:

@app.route('/api/attendance/<string:date_from>/<string:date_to>',methods=['GET'])
def get_attend_date_date(date_from,date_to):
data = db.session.query(Attendance).filter(Attendance.date.between(date_from,date_to)).order_by(Attendance.date,Attendance.time)
attendance_schema = AttendanceSchema(many=True)
data = attendance_schema.dump(data).data
return jsonify({'attendance':data})

输出

{
"attendance": [
{
"Device": 4,
"date": "2016-01-18",
"id": 18805,
"time": "00:49:00",
"user": 30025
},
{
"Device": 4,
"date": "2016-01-18",
"id": 18902,
"time": "00:49:00",
"user": 30045
},

但是
我正在获取用户 uid ,我想返回 user.name

最佳答案

我使用flask_marshmallow序列化数据,然后将其作为josn发送,为了能够发送用户名,我必须从用户模式中嵌套名称,如下所示:

class UsersSchema(ma.Schema):
name = fields.String(dump_only=True)

class AttendanceSchema(ma.Schema):
date = fields.Date(dump_only=True)
user = fields.Nested(UsersSchema)

关于mysql - 如何在flask sqlalchemy中选择列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35011917/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com