5

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is pretty cool, thanks for sharing! I use it to get total count in one query: count(1) OVER() AS total_count

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.