'Get all column names from joined SQLAlchemy tables

I have a small database with 3 tables in SQLAlchemy (ORM). I want to query all the data, joining the 3 tables and output this to a CSV, so I need to get the column names for each of the tables to be the CSV headings.

Example of tables linked together through foreign keys and relationships:

class Person(Base):
    __tablename__ = 'people'
    id = Column(Integer, primary_key=True)
    email = Column(String)
    name = Column(String)

    orders = relationship("Order",
                       back_populates='person',
                       cascade="all, delete-orphan")

class Order(Base):
    __tablename__ = "orders"
    id = Column(String, primary_key=True)
    person_id = Column(String, ForeignKey("people.id"))
    date = Column(Date)

    person = relationship("Person",
                     back_populates='orders')
    items = relationship("Item",
                       back_populates='order',
                       cascade="all, delete-orphan")

class Item(Base):
    __tablename__ = "items"
    order_id = Column(Integer, ForeignKey("orders.id"))
    price = Column(Float)

    order = relationship("Order",
                     back_populates='orders')

If I run results = session.query(Person).join(Order).join(Item).all() the results contains all my 'Person' entries and I can get the column names for that table using results[0].__dict__.keys() or Person.__mapper__.columns, but I want the columns from the Order and Item tables as well.

I want to end up with a CSV like this, where person and orders may be repeated many times as there are many items in one order and many orders for one person:

personID name email orderID Date itemID price
1 name email 1 Date 1 3.00
1 name email 1 Date 2 6.00
1 name email 2 Date 3 4.00
1 name email 2 Date 4 3.50
2 name email 3 Date 5 7.00
2 name email 4 Date 6 2.00
2 name email 4 Date 7 1.00


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source