如何在烧瓶中一起给予独特的?

How to give unique together in flask?

我在 Flask 中定义一个 table 就像

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.
)

但这不起作用。

我想你可以参考一个老话题

代码如下:

# 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'),
    )

您对 post 和 sqlalchemy 官方文档的 link 做了一些解释。

感谢 Van post编者。