python sqlalchemy 查询result 转换成自定义类

当然,很多时候我们需要用到sql语句,执行的sql返回的结果我们也想映射到class object。此demo包括max,group_by等函数。以下是博主自己想的一种方法,但觉得应该有更好的实现方式,如果您知道,烦请告诉我,谢谢

from sqlalchemy import *
class cc(object):
    def __init__(self,name,country,id,count):
        self.name=name
        self.id=id
        self.country=country
        self.maxvalue=count

engine=create_engine('postgresql://{}:{}@{}:{}/{}'.format('postgres','postgres','localhost',5432,'postgres'))
metadata = MetaData(engine)
foo = Table('slams', metadata, autoload=True)
bar = Table('slamschild', metadata, autoload=True)
result=select([foo.c.name.label('name'),foo.c.country,bar.c.id,func.max(foo.c.value).label('count')],bar.c.value==foo.c.value).group_by(foo.c.name,bar.c.id).execute().fetchall()
for item in result:
    print(item)
result=[cc(a,b,c,d) for a,b,c,d in result]

for item in result:
    print("country"+ item.country+'name'+item.name+'id'+str(item.id))

c=foo.update().where(foo.c.value==1).values(country='nihao')
engine.execute(c)
person = ('Alisone','Vctoria','Brenda','Rchel','Trevor')
person = tuple(sorted(person,key=lambda x:len(x)))
print(person)
persion=filter(lambda x:len(x)>6,list(person))
print(tuple(persion))

https://marshmallow-sqlalchemy.readthedocs.io/en/latest/

你可能感兴趣的:(Python)