I have 2 models/tables, one a Project, and the other a Level. One project can have multiple levels, but each level can only belong to one Project. A level must have a floor (int), that needs to be unique for each project. In other words, (project.project_id, level.floor) must be unique. How do I enforce this type of constraint using SQLAlchemy?
I have removed all unnecessary fields from the 2 models:
class Project(Base):
__tablename__ = "project"
project_id = Column(Integer, primary_key=True)
class Level(Base):
__tablename__ = "level"
level_id = Column(Integer, primary_key=True)
floor = Column(Integer)
project_id = Column(Integer, ForeignKey("project.project_id"))
project = relationship(
"Project",
backref="levels", #! might see an error here (project does not exist)
cascade="all, delete",
)
UniqueConstraint("project_id", "floor", name="project_level_floor")
UPDATE:
This appears to a SQLite issue, as I have the exact same code in a different app that uses Postgres and that enforces this unique constraint.