Understanding MetaData() from SQLAlchemy in Python

后端 未结 1 563
暗喜
暗喜 2021-02-04 08:21

I am trying to understand what the MetaData() created object is in essence. It is used when reflecting and creating databases in Python (using SQLAlchemy package).

Cons

相关标签:
1条回答
  • 2021-02-04 08:51

    I think you asked how does python (SQLAlchemy you presumably mean) connect the table to the metadata and the metadata to the database and engine.

    So database tables in SQLAlchemy belong (are linked to) a metadata object. The table adds itself to the metadata; there is a tables property on the metadata object that acts a lot like a list:

    >>> len(models.Base.metadata.tables)
        22
    

    The reason you need the metadata object is:

    • To have a single unit of work for creating and dropping related tables

    • To have a place to collect all the results of a reflection operation

    • To sort related tables based on their dependencies so that foreign key constraints can be created in the right order.

    So, the metadata object contains SQLAlchemy'sidea of what it thinks a database might look like. It's typically populated either from reflection or from you creating table objects (possibly through the declarative base extension).

    You can directly associate a metadata object with a real database engine by setting the bind parameter in the metadata constructor. Alternitevly, you can make the link when you use the metadata either in create calls or in reflection calls.

    0 讨论(0)
提交回复
热议问题