I have the following code:
from sqlalchemy import (create_engine, Column, String,
Integer, Float, ForeignKeyConstraint)
from sqlalchemy.orm import (DeclarativeBase, relationship)
class Base(DeclarativeBase):
pass
class Process(Base):
__tablename__ = 'process'
run_id = Column(Integer, primary_key=True)
process_id = Column(String, primary_key=True)
process_attrs = Column(String, nullable=True)
class ProcessWeekly(Base):
__tablename__ = 'process_weekly'
run_id = Column(Integer, primary_key=True)
process_id = Column(String, primary_key=True)
week = Column(Integer, primary_key=True)
loss_factor = Column(Float, default=1.0)
process = relationship(Process)
__table_args__ = (
ForeignKeyConstraint([run_id, process_id],
[Process.run_id, Process.process_id]),
)
class Location(Base):
__tablename__ = "location"
run_id = Column(Integer, primary_key=True)
location_id = Column(String, primary_key=True)
engine = create_engine("sqlite:///test.db")
Base.metadata.create_all(engine, tables=[ProcessWeekly.__table__])
What this code creates is just the ProcessWeekly
table. What I wish to create is, since, the ProcessWeekly
table has a foreignkey constraint on the Process
table, I’d want to create that as well. Location
table doesn’t have any foreignkey dependency, hence, I do not want to create it.
This is just a simple example to suggest 1 level of Foreignkey constraint. However, in my use case, it’ll be multi-level dependency, i.e., Process
table can itself has a ForeignKey dependency on some further level tables.
How can I modify my code to create all the tables suggested in argument of the Base.metadata.create_all(engine, tables=[...])
and all the further downstream tables with foreignkey dependency?
I’m using sqlalchemy==2.0.25
.