Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to give unique together in flask?

I am defining a table in Flask like

groups = db.Table(
    "types",
    db.Column("one_id", db.Integer, db.ForeignKey("one.id")),
    db.Column("two_id", db.Integer, db.ForeignKey("two.id")),
    UniqueConstraint('one_id', 'two_id', name='uix_1') #Unique constraint given for unique-together.
)

But this is not working.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you can refer to an old topic https://stackoverflow.com/a/10061143/18269348

Here is the code :

# version1: table definition
mytable = Table('mytable', meta,
# ...
    Column('customer_id', Integer, ForeignKey('customers.customer_id')),
    Column('location_code', Unicode(10)),
    UniqueConstraint('customer_id', 'location_code', name='uix_1')
    )
# or the index, which will ensure uniqueness as well
Index('myindex', mytable.c.customer_id, mytable.c.location_code, unique=True)

# version2: declarative
class Location(Base):
    __tablename__ = 'locations'
    id = Column(Integer, primary_key = True)
    customer_id = Column(Integer, ForeignKey('customers.customer_id'), 
    nullable=False)
    location_code = Column(Unicode(10), nullable=False)
    __table_args__ = (UniqueConstraint('customer_id', 'location_code', 
    name='_customer_location_uc'),
    )

You have a little explanation on the post and a link to the official documentation of sqlalchemy.

Thanks to Van who posted that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading