1

我是 Python 新手。这是我的代码

class Test(Base):
     __tablename__ = 'test'
     __public__ = ('my_id', 'name')
     my_id = Column(Integer, primary_key=True)
     name = Column(String)
     def __init__(self, id, name):
         self.my_id = id
         self.name = name
     def __repr__(self):
         return "<User('%d','%s')>" % (self.id, self.name)
     @property   
     def json(self):    
         return to_json(self, self.__class__)

output=[]
users= cess.query(Test).order_by(Test.my_id).distinct().all()
for c in users:
    output.append(c.json)

print json.dumps(output)

但这不是正确的json?我想将 for 循环中的所有 json 对象添加到适当的 json 数组中,以便客户端可以循环它?我怎样才能做到这一点 ?

4

1 回答 1

1

您可以从查询结果中构建字典列表。在模型上定义to_dict方法(取自此处):

class Test(Base):
   ...

   def to_dict(self):
       return {c.name: getattr(self, c.name) for c in self.__table__.columns}

然后,制作一个字典列表并将其转储到 json:

users = cess.query(Test).order_by(Test.my_id).distinct().all()
output = [c.to_dict() for c in users]

print json.dumps(output)

另见:

于 2013-10-01T19:24:47.867 回答