您的位置:首页技术文章
文章详情页

python - flask-sqlalchemy 怎么设置json格式的字段

【字号: 日期:2022-06-13 10:19:25浏览:17作者:猪猪

问题描述

flask-sqlalchemy 怎么设置json格式的字段

问题解答

回答1:

有两种方法:1.sqlalchemy中PickleType可以对应任何python对象.2.可以通过编写方法的方式生成json.

具体代码如下:

#!usr/bin/env python# coding:utf-8from flask import Flaskfrom flask_sqlalchemy import SQLAlchemyapp = Flask(__name__)app.config[’SQLALCHEMY_DATABASE_URI’] = ’mysql://root:psw@localhost/test_json’app.config[’SQLALCHEMY_TRACK_MODIFICATIONS’] = Truedb = SQLAlchemy(app)class Users(db.Model): __tablename__ = ’users’ user_id = db.Column(db.Integer, primary_key=True) user_info = db.Column(db.PickleType) def __repr__(self):return self.user_infoclass Students(db.Model): __tablename__ = ’students’ student_id = db.Column(db.Integer, primary_key=True) student_name = db.Column(db.String(80), unique=True) student_age = db.Column(db.Integer) student_sex = db.Column(db.String(20)) def to_json(self):json_student = { ’student_id’: self.student_id, ’student_name’: self.student_name, ’student_sex’: self.student_sex, ’student_age’: self.student_age}return json_student def __repr__(self):return ’%r’ % self.student_idif __name__ == '__main__': #-----------------------生成----------------------- USER_INFO = {'name':'nisiwa', 'mail':'2222233333@qq.com'} db.create_all() USER = Users(user_info=USER_INFO) STUDENT = Students(student_name='nisiwa', student_age='28', student_sex='male') db.session.add(USER) db.session.add(STUDENT) db.session.commit() #-----------------------调用------------------------ user = Users.query.filter_by(user_id=1).first() student = Students.query.filter_by(student_id=1).first() print ’student:’, student.to_json() print ’user:’, user.user_info

结果如下:python - flask-sqlalchemy 怎么设置json格式的字段

标签: Python 编程
相关文章: