'SQLAlchemy multi column constraint

I have a number of tables in different schemas, I used the pattern from the docs. Some of my tables require multi column constraints and it was unclear what the dictionary key would be for declaring that unique constraint as they mention in the section above

In my model below, I'd like to create a unique constraint with name, key, org. I currently have to do this in sql...

class Parent(Base):
  __tablename__ = 'parent'
  __table_args__ = {'schema': 'example'}

  id = Column(Integer, primary_key=True)
  name = Column(String(512))
  key = Column(String())
  org = Column(String(36))


Solution 1:[1]

I think I encountered that issue a while back. If I remember correctly, it was just a matter of moving the "schema dict" to inside a tuple which also contains your constraints.

I can try to dig further if that does not work, but the documentation seems to agree that using declarative table configuration via __table_args__ can be a tuple containing positional arguments (like constraints) and as a final argument a dict with keyword arguments like schema is for Table.

class Parent(Base):
    __tablename__ = 'parent'
    __table_args__ = (
        UniqueConstraint('name', 'key', 'org'),
        {'schema': 'example'},
    )

    id = Column(Integer, primary_key=True)
    name = Column(String(512))
    key = Column(String())
    org = Column(String(36))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1