2016-01-26 106 views
0

如何從另一個表,而不是ID選擇一個名稱列, 例如:如何在燒瓶SQLAlchemy的選擇列

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}) 

OUTPUT

{ 
    "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

回答

0

正在使用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)