[Python] How to insert NULL AS alias "dummy columns" for UNION in SQLAlchemy?

Discussão em 'Python' iniciado por Stack, Abril 13, 2025.

  1. Stack

    Stack Membro Participativo

    Context


    Suppose I have a model class in SQLAlchemy that looks something like this:

    class A():
    id = Column('id', Integer, primary_key=True, autoincrement=True)
    title = Column('Title', String, nullable=False)
    type = Column('type', String)
    message = Column('message', String, nullable=False)


    If I filter this model class using query() like this: q = session.query(A) The output is the following:

    SELECT
    "A"."id" AS "A_id", "A"."title" AS "A_title", "A"."type" AS "A_type", "A"."message" AS "A_message"
    FROM "A"

    Problem


    I need to perform a UNION with another query that contains the same number of columns, in the same order. I need my query to be this:

    SELECT
    NULL AS "A_id", NULL AS "A_title", NULL AS "A_type", NULL AS "A_message"
    FROM "A"


    I've already tried: q = session.query(A, null()) but that just returns:

    SELECT
    "A"."id" AS "A_id", "A"."title" AS "A_title", "A"."type" AS "A_type", "A"."message" AS "A_message", NULL AS anon_1
    FROM "A"

    Question


    SELECT
    NULL AS "A_id", NULL AS "A_title", NULL AS "A_type", NULL AS "A_message"
    FROM "A"


    How can I achieve the query shown above (inserting NULL AS as an alias)?

    Continue reading...

Compartilhe esta Página