Can I assign values in RowProxy using the sqlalchemy?

前端 未结 2 1773
盖世英雄少女心
盖世英雄少女心 2020-12-10 02:30

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

         


        
相关标签:
2条回答
  • 2020-12-10 02:50

    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.

    0 讨论(0)
  • 2020-12-10 02:56

    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']
    
    0 讨论(0)
提交回复
热议问题