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.
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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With