简体   繁体   中英

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

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.

Please refer to the peewee docs: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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