Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assign values in RowProxy using the sqlalchemy?

When I want to display some data in the web, the data need makeup, and I don't know how to achieve, here is the code:

from sqlalchemy import create_engine

engine = create_engine('mysql://root:111@localhost/test?charset=utf8')
conn = engine.connect()

articles = conn.execute('SELECT * FROM article')
articles = articles.fetchall()

for r in articles:
    r['Tags'] = r['Keywords']

It tips that: 'RowProxy' object does not support item assignment.

What should I do for that?

The table 'article' contains the column 'Keywords', and not contains the column 'Tags'.

like image 534
Tony Avatar asked May 14 '12 17:05

Tony


People also ask

What SQLAlchemy execute return?

SQLAlchemy execute() return ResultProxy as Tuple, not dict.

Can you create a database with SQLAlchemy?

Creating and Inserting Data into TablesBy passing the database which is not present, to the engine then sqlalchemy automatically creates a new database.

What is Create_engine in SQLAlchemy?

The create_engine() method of sqlalchemy library takes in the connection URL and returns a sqlalchemy engine that references both a Dialect and a Pool, which together interpret the DBAPI's module functions as well as the behavior of the database.

Which DB is used in SQLAlchemy?

Supported Databases. SQLAlchemy includes dialects for SQLite, Postgresql, MySQL, Oracle, MS-SQL, Firebird, Sybase and others, most of which support multiple DBAPIs.


2 Answers

You can make a dict out of your RowProxy, which would support item assignment.

For example:

result_proxy = query.fetchall()
for row in result_proxy:
    d = dict(row.items())
    d['Tags'] = d['Keywords']
like image 146
jd. Avatar answered Oct 20 '22 15:10

jd.


One nice trick with this is to use a subclass of a dict:

class DBRow(dict):
    def __getattr__(self, key):
        """make values available as attributes"""
        try:
            return self[key]
        except KeyError as error:
            raise AttributeError(str(error))

   @property
   def something_calculated(self):
       return self.a + self.b

row = DBRow(result_proxy_row, additional_value=123)
row["b"] = 2 * row.b
print something_calculated

The benefit of this is, that you can access the values still as attributes, plus you can have properties, which is a nice way to cleanup and massage the data coming from the database.

like image 23
yacc143 Avatar answered Oct 20 '22 17:10

yacc143