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.

1 Answer

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.

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like