Creating unique index with peewee for table with foreign key
Asked Answered
B

1

5

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.

Boudreaux answered 3/9, 2015 at 13:2 Comment(0)
G
11

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.

Glycerinate answered 16/6, 2016 at 8:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.