简体   繁体   English

使用外键为带有外键的表创建唯一索引

[英]Creating unique index with peewee for table with foreign key

Say that I have a table called TBL_ACCOUNT which contains all of my users, and a table called TBL_EMAIL_SUBSCRIPTION where it contains the feeds that a user is subscribed to. 假设我有一个名为TBL_ACCOUNT的表,其中包含我的所有用户,还有一个名为TBL_EMAIL_SUBSCRIPTION的表,其中包含用户已订阅的提要。 I'm trying to make it so that there can only be one entry of each user+feed combination, so user1 can only be subscribed to feed1 once, but user1 can be subscribed to feed1 and feed2 simultaneously. 我正在尝试使其每个用户+ feed组合中只有一个条目,因此user1只能订阅一次feed1,但是user1可以同时订阅feed1和feed2。

This is what my model looks like: 这是我的模型的样子:

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

I have also tried just using "USER" for the indexes, but that didn't work out as the database still received duplicates. 我也尝试过仅使用“ USER”作为索引,但是由于数据库仍然收到重复项,因此无法解决。

Please refer to the peewee docs: http://docs.peewee-orm.com/en/latest/peewee/models.html#indexes-and-constraints 请参考peewee文档: http ://docs.peewee-orm.com/en/latest/peewee/models.html#indexes-and-constraints
In your case it should look like this: 在您的情况下,它应如下所示:

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

Note the use of commas! 注意使用逗号! They are very important, because indexes are a tuple of tuples. 它们非常重要,因为索引是元组的元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM