python SQLAlchemy实体转字典

python SQLAlchemy实体转字典,第1张

1、实体基类

class ModelBase(object):
    fields = None

    def __init__(self):
        if not self.__class__.fields:
            self.__class__.fields = [x.key for x in self.__mapper__.attrs]

    def __iter__(self):
        if not self.__class__.fields:
            self.__class__.fields = [x.key for x in self.__mapper__.attrs]
        return next(self)

    def __next__(self):
        for key in self.__class__.fields:
            value = getattr(self, key)
            yield key, value

2、实体类

class Arrive(ModelBase, db.Model):
	__tablename__ = "Arrive"
	ID = db.Column(db.BigInteger, primary_key=True, autoincrement=False, info='ID')
	REG = db.Column(db.String(10), nullable=False, info='编号')

3、测试

def test_arrive(self):
	entity = Arrive()
	entity.ID = 1
	entity.REG = 'T320'

	js = json.dumps(dict(entity))
	print(js)

	self.assertTrue(js)	

4、输出结果

{"ID": 1, "REG": "T320"}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/727685.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存