有没有办法将sqlalchemy orm实例转储到json?

时间:2014-03-11 03:12:39

标签: python json sqlalchemy

我在python中编写了这个函数来将对象转储到json。是否有更好,更经过测试的方法来使用库?

def model_jsonify(self,instance):
    from sqlalchemy.orm import class_mapper , ColumnProperty
    attrs = [prop.key for prop in class_mapper(instance.__class__).iterate_properties if isinstance(prop, ColumnProperty)]

    r = dict()

    for attr in attrs :
        c = getattr(instance,attr)
        assert not c is None
        r[attr] = c

    return r

1 个答案:

答案 0 :(得分:0)

为了完成这个问题,我写了这段代码。您可以查询简单的ORM对象或列表(查询连接时的结果)。但是你不能序列化单个字段(比如只用一些fiels查询连接)

def model_jsonify(self,instance):
    from sqlalchemy.orm import class_mapper , ColumnProperty
    from sqlalchemy.util import KeyedTuple

    if isinstance(instance,KeyedTuple) :
        attrs = []
        r = dict()
        for i in instance :         
            modelname = type(i).__name__.lower()
            attrs = [prop.key for prop in class_mapper(i.__class__).iterate_properties if isinstance(prop, ColumnProperty)]
            r[modelname] = dict((c, getattr(i, c)) for c in attrs)
        return r

    else :
        attrs = [prop.key for prop in class_mapper(instance.__class__).iterate_properties if isinstance(prop, ColumnProperty)]
        r = dict()
        modelname = type(instance).__name__.lower()
        r[modelname] = dict((c, getattr(instance, c)) for c in attrs)
        return r

这是我用两个查询编写的一个小测试:

purchaseorder = mi.session.query(PurchaseOrder).first()
assert purchaseorder != None

j = mi.model_jsonify (purchaseorder)
assert not j is None
assert isinstance(j,dict)

assert j['purchaseorder']['name'] == 'january'

bompurchaseorderlines = mi.session.query(BoMPurchaseOrderLine,SupplierLine).join(SupplierLine).all()
assert not bompurchaseorderlines is None

for purchaseorder in bompurchaseorderlines :
    j = mi.model_jsonify (purchaseorder)