Skip to content
Advertisement

why UniqueConstraint doesn’t work in flask_sqlalchemy

I want an alternative of Django’s unique_together in flask, seems UniqueConstraint is what I’m looking for, but doesn’t work for me.

here is the example:

JavaScript

Test it:

JavaScript

I also tried with:

JavaScript

not work either, what’s wrong with it?

Advertisement

Answer

An instance of UniqueConstraint is iterable and in this case seems to stop iteration immediately, so

JavaScript

results in an empty tuple, when you wanted a tuple that contains 1 item, the constraint instance. Use

JavaScript

or any other variation instead. As to why the latter form does not work, you must apply table-level constraint objects using __table_args__ in declarative, if using names, or there will be no connection between the constraint construct and the Table backing the declarative model. If using Column objects the constraint can be created just about where ever, the connection is made through the Column object to the Table. There is also a third option: Table.append_constraint() method, which you can access through the model class’ __table__ attribute.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement