Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 734
Crushing Avatar asked Oct 23 '25 23:10

Crushing


1 Answers

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))
like image 173
ljmc Avatar answered Oct 25 '25 14:10

ljmc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!