Search code examples
pythondjangopostgresqlindexingorm

django - is UniqueConstraint with multi fields has same effect as Index with same field?


I wrote a django model that you can see below, I want to know having the UniqueConstraint is enough for Search and Selecting row base on user and soical type or I need to add the Index for them. if yes what is the different between them becuse base on my search the UniqueConstraint create an Unique Index on DB like posgresql.

model:

class SocialAccount(Model):
    """Social account of users"""

    added_at: datetime = DateTimeField(verbose_name=_("Added At"), auto_now_add=True)
    user = ForeignKey(
        to=User,
        verbose_name=_("User"),
        db_index=True,
        related_name="socials",
    )
    type = PositiveSmallIntegerField(
        verbose_name=_("Type"),
        choices=SocialAcountType,
    )

    class Meta:
        constraints = UniqueConstraint(
            # Unique: Each User Has Only one Social Account per Type
            fields=(
                "user",
                "type",
            ),
            name="user_social_unique",
        )
        # TODO: check the UniqueConstraints is enough for index or not
        indexes = (
            Index(  # Create Index based on `user`+`type` to scan faster
                fields=(
                    "user",
                    "type",
                ),
                name="user_social_index",
            ),
        )

base on the above description I searched but I can't find any proper document to find how django act and we need extra index for them if they are a unique togher already?

Note: I know there are some other questions that are similar but they can't answer my question exactly


Solution

  • UniqueConstraint is enough.

    I was also confused about this question before. I did some testing and found the description from pg's documentation. https://www.postgresql.org/docs 11.6. Unique Indexes

    PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.