使用外键为 table 使用 peewee 创建唯一索引

Creating unique index with peewee for table with foreign key

假设我有一个名为 TBL_ACCOUNT 的 table,其中包含我的所有用户,还有一个名为 TBL_EMAIL_SUBSCRIPTION 的 table,其中包含用户的提要订阅了。我正在努力使每个用户+提要组合只能有一个条目,因此 user1 只能订阅 feed1 一次,但 user1 可以同时订阅 feed1 和 feed2。

这是我的模型的样子:

class TBL_ACCOUNT(BaseModel):
    USERNAME = CharField(unique=True)
    PASSWORD = CharField()
    EMAIL = CharField(unique=True)

class TBL_EMAIL_SUBSCRIPTION(BaseModel):
    USER = ForeignKeyField(TBL_ACCOUNT)
    FEED = CharField()

    class Meta:
        indexes = (("USER_id", "FEED", True))

我也试过只使用 "USER" 作为索引,但没有成功,因为数据库仍然收到重复项。

请参考 peewee 文档:http://docs.peewee-orm.com/en/latest/peewee/models.html#indexes-and-constraints
在您的情况下,它应该如下所示:

class Meta:
    indexes = (
        (("USER_id", "FEED"), True),
    )

注意逗号的使用!它们非常重要,因为索引是元组的元组。