Creating Partial Indexes with Django 1.7

≯℡__Kan透↙ 提交于 2019-11-26 23:14:54

问题


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 title, blog & category to be unique. However if category is not provided, the combination of title & blog should still be unique.

class Post(models.Model):
    title = models.CharField(max_length=200)
    blog = models.ForeignKey(Blog)
    category = models.ForeignKey(Category, null=True, blank=True)

I can achieve this constraint with partial indexes (like the SQL shown below). Where do I add this code if I'm using Django 1.7 migrations?

CREATE UNIQUE INDEX idx1 
  ON Post (title, blog_id, category_id) 
  WHERE category_id IS NOT NULL;

CREATE UNIQUE INDEX idx2 
  ON Post (title, blog_id)
  WHERE category_id IS NULL;

回答1:


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"], condition=Q(category__isnull=False)),
            UniqueConstraint(fields=["title", "blog"], 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.




回答2:


You could just provide an unique_together like so:

class Post(models.Model):
    title = models.CharField(max_length=200)
    blog = models.ForeignKey(Blog)
    category = models.ForeignKey(Category, null=True, blank=True)

class Meta:
    unique_together = ("title", "blog", "category")

NULLs for category will work how you want in that if not set then title/blog has to be unique.

https://docs.djangoproject.com/en/1.8/ref/models/options/#unique-together



来源:https://stackoverflow.com/questions/26410488/creating-partial-indexes-with-django-1-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!