Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy from_statement dynamic attributes for python objects

I have such model:

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 generate RAW SQL for very difficult SELECT from db with additional dynamic data.

For example it 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 generate list of python objects Test, but how I can fill attribute additional for these python objects?

I don't want store NULL column additional in database.

I want create dynamic additional data with SQL and add it to python objects.

Help please.

Thanks.

like image 943
lestat Avatar asked Nov 14 '22 16:11

lestat


1 Answers

Do this:

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 (Test object,additional) structure.

like image 91
Arad Avatar answered Jan 14 '23 08:01

Arad