Creating Partial Indexes with Django 1.7

前端 未结 2 748
小鲜肉
小鲜肉 2020-12-05 19:08

The documentation for Django 1.7 mentions RunSQL classes can be used to create partial indexes on your tables. I have a table where I want the combination of

2条回答
  •  生来不讨喜
    2020-12-05 20:03

    Django 2.2 and later

    As of version 2.2 Django supports declarative partial unique indexes on databases that support them (PostgreSQL and SQLite). So you could do something like:

    from django.db.models import Model, Q, UniqueConstraint
    
    class Post(Model):
        ...
        class Meta:
            constraints = [
                UniqueConstraint(
                    fields=["title", "blog", "category"],
                    name="idx1",
                    condition=Q(category__isnull=False)),
                UniqueConstraint(
                    fields=["title", "blog"], 
                    name="idx2",                    
                    condition=Q(category__isnull=True)),
            ]
    

    Django 2.1 and earlier

    In older versions you need to do this with migrations. First create a new, empty migration file:

    python manage.py makemigrations --empty yourappname
    

    Then, for each index add an appropriate RunSQL line:

    operations = [
        migrations.RunSQL("CREATE UNIQUE INDEX..."),
        migrations.RunSQL("CREATE UNIQUE INDEX..."),
    ]
    

    Finally, run migrate.

提交回复
热议问题