SQLAlchemy: is there a good automatic way to rename columns

I have been using SQLAlchemy ORM for several days, and I'm looking for a way to get the tablename prefix in the results of Session.query() .

For instance:

 myId = 4 ... data = session.query(Email.address).filter(Email.id==str(myId)).one() print data.keys() 

This will display:

 ("address",) 

And I would like to get something like:

 ("Email.address",) 

Is there a way to do this without changing the class attributes and table column names. This example is a bit fictitious, but for a more general purpose, I would like to prefix all column names by table names as a result, to make sure that the results are always in the same format, even if there are join queries. I read things about aliased() , there are a lot of posts here, but nothing satisfied me. Can someone please enlighten me on this?

Thanks.


EDIT:

Thanks so much for your answer @alecxe. I finally managed to do what I wanted. Here is the first batch of my code, perhaps a lot will improve:

 query = self.session.query(Email.address,User.name) cols = [{str(column['name']):str(column['expr'])} for column in query.column_descriptions] someone = query.filter(User.name==str(curName)).all() r = [] for res in someone : p = {} for c in map(str,res.__dict__): if not c.startswith('_'): for k in cols: if c == k.keys()[0]: p[k[c]] = res.__dict__[c] r.append(p) print r 

Output:

 [{'Email.address': u' john@foobaz.com ', 'User.name': u'John'}] 
+4
source share
1 answer

Try column_descriptions :

 query = session.query(Email.address) print [str(column['expr']) for column in query.column_descriptions] # should print ["Email.address"] data = query.filter(Email.id==str(myId)).one() 

Hope this helps.

+2
source

Source: https://habr.com/ru/post/1481724/


All Articles