sqlalchemy結果轉json


網上搜了下,http://blog.csdn.net/liu_xing_hui/article/details/8956107
介紹的很詳細,自動一個Encoder給json的dump方法使用,能夠實現queryresult轉json

import json
from sqlalchemy.ext.declarative import DeclarativeMeta
from datetime import datetime

def new_alchemy_encoder():
    _visited_objs = []

    class AlchemyEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj.__class__, DeclarativeMeta):
                # don't re-visit self
                if obj in _visited_objs:
                    return None
                _visited_objs.append(obj)

                # an SQLAlchemy class
                fields = {}
                for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
                    data = obj.__getattribute__(field)
                    try:
                        if isinstance(data, datetime):
                            data = data.strftime('%Y-%m-%d %H:%M:%S')
                        json.dumps(data)  # this will fail on non-encodable values, like other classes
                        fields[field] = data
                    except TypeError:
                        fields[field] = None
                return fields

            return json.JSONEncoder.default(self, obj)
    return AlchemyEncoder
UnReadMsg = self.db.query(Message).filter(Message.uid == self.uid)
msgs = []
for msg in UnReadMsg:
    msgs.append(msg)
UnReadMsg = json.dumps(msgs, cls=new_alchemy_encoder(), check_circular=False)

但是新版的sqlalchemy中的queryresult對象加入了json屬性,直接能得到json串,棒棒噠

UnReadMsg = self.db.query(Message).filter(Message.uid == self.uid)
msgs = []
for msg in UnReadMsg:
    msgs.append(msg.json)
print(msgs)
return JsonResponse(self, 50000, data=msgs)   

直接拿到結果爽的不要不要的,不過還是要知道這個dump方式是怎么實現的,這樣以后也能處理更復雜的情況

{
  "code": 50000,
  "data": [
    {
      "content": "你好啊",
      "entry_date": "2017-2-20 20:40",
      "msg_id": "2",
      "msg_readstatus": "1",
      "msg_sendstatus": "1",
      "msg_type": "1",
      "read_time": "",
      "send_time": "2017-2-20 20:40",
      "stamped": "0",
      "suid": "3",
      "uid": "1"
    },
    {
      "content": "好的很",
      "entry_date": "2017-2-20 20:41",
      "msg_id": "3",
      "msg_readstatus": "1",
      "msg_sendstatus": "1",
      "msg_type": "1",
      "read_time": "",
      "send_time": "2017-2-20 20:41",
      "stamped": "0",
      "suid": "2",
      "uid": "1"
    }
  ],
  "msg": null
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM