Sqlalchemy from_statement dynamic attributes for python objects

I have a model like this:

class Test(db.Model, UnicodeMixin): __tablename__ = 'test' id = db.Column(db.Integer, primary_key=True) subject = db.Column(db.String(512), nullable=False) additional = None def __unicode__(self): return u'<Test {0}>'.format(self.id) 

Some code generates RAW SQL for very complex SELECT from a database with additional dynamic data.

For example, it’s like:

 db.session.query(Test).from_statement("SELECT test.id AS test_id, test.subject AS test_subject, 99 AS additional FROM test").all() 

It generates a list of Python Test objects, but how do I populate the additional attribute for these Python objects?

I do not want to store the NULL additional column in the database.

I want to create dynamic additional data using SQL and add it to Python objects.

Help me please.

Thank you

+5
source share
1 answer

Do it:

 db.session.query(Test, "additional").from_statement( """ SELECT test.id AS test_id, test.subject AS test_subject, 99 AS additional FROM test """ ).all() 

It will return a list of tuples in the structure (test object, optional).

0
source

All Articles