如何选择flask sqlalchemy中的列

时间:2016-01-26 10:40:00

标签: mysql database flask flask-sqlalchemy

如何从另一个表而不是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
    },

BUT
我得到用户uid,我想返回user.name

1 个答案:

答案 0 :(得分:0)

在将数据发送为josn之前使用flask_marshmallow来序列化数据,为了能够发送用户名,我必须将用户模式中的名称嵌套如下:

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

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