【问题标题】:How to give unique together in flask?如何在烧瓶中一起赋予独特性?
【发布时间】:2022-02-23 16:28:53
【问题描述】:

我正在像 Flask 中定义一个表

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

但这不起作用。

【问题讨论】:

标签: python django flask


【解决方案1】:

我觉得你可以参考一个老话题https://stackoverflow.com/a/10061143/18269348

代码如下:

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

你在帖子上有一点解释和sqlalchemy官方文档的链接。

感谢发布此内容的 Van。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    相关资源
    最近更新 更多