Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of __table_args__ in sqlalchemy?

I have no experience with sqlalchemy, and I have the following code:

class ForecastBedSetting(Base):
    __tablename__ = 'forecast_bed_settings'
    __table_args__ = (
        Index('idx_forecast_bed_settings_forecast_id_property_id_beds',
              'forecast_id', 'property_id',
              'beds'),
    )

    forecast_id = Column(ForeignKey(u'forecasts.id'), nullable=False)
    property_id = Column(ForeignKey(u'properties.id'), nullable=False, index=True)
    # more definition of columns

Although I have checked this, I cannot understand what is the purpose of __table_args__, so I have no clue what this line is doing:

__table_args__ = (
    Index('idx_forecast_bed_settings_forecast_id_property_id_beds',
    'forecast_id', 'property_id',
    'beds'),
)

Could somebody please explain me what is the purpose of __table_args__, and what the previous piece of code is doing.

like image 308
lmiguelvargasf Avatar asked Apr 17 '17 16:04

lmiguelvargasf


People also ask

What is the use of MetaData in SQLAlchemy?

Metadata contains definitions of tables and associated objects such as index, view, triggers, etc. Hence an object of MetaData class from SQLAlchemy Metadata is a collection of Table objects and their associated schema constructs.

What does base MetaData Create_all do?

create_all() creates foreign key constraints between tables usually inline with the table definition itself, and for this reason it also generates the tables in order of their dependency.

What is foreign key in SQLAlchemy?

A foreign key in SQL is a table-level construct that constrains one or more columns in that table to only allow values that are present in a different set of columns, typically but not always located on a different table.

How do you declare a primary key in SQLAlchemy?

To create a composite primary key, set primary_key to True on each column involved in the key. A boolean argument when set to False adds NOT NULL constraint while creating a column. Its default value is True .


1 Answers

This attribute accommodates both positional as well as keyword arguments that are normally sent to the Table constructor.

During construction of a declarative model class – ForecastBedSetting in your case – the metaclass that comes with Base creates an instance of Table. The __table_args__ attribute allows passing extra arguments to that Table. The created table is accessible through

ForecastBedSetting.__table__

The code defines an index inline, passing the Index instance to the created Table. The index uses string names to identify columns, so without being passed to a table SQLAlchemy could not know what table it belongs to.

like image 76
Ilja Everilä Avatar answered Nov 13 '22 11:11

Ilja Everilä