使用Django 1.7创建部分索引

时间:2021-12-14 04:14:51

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.

Django 1.7的文档提到可以使用RunSQL类在表上创建部分索引。我有一个表,我希望标题、博客和类别的组合是唯一的。但是如果没有提供类别,标题和博客的组合仍然是唯一的。

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?

我可以使用部分索引(如下面所示的SQL)实现这个约束。如果我使用Django 1.7迁移,我应该在哪里添加这些代码?

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;

2 个解决方案

#1


18  

First create a new, empty migration file:

首先创建一个新的空迁移文件:

python manage.py makemigrations --empty yourappname

Then, for each index add an appropriate RunSQL line:

然后,为每个索引添加适当的RunSQL行:

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

Finally, run migrate.

最后,运行迁移。

#2


0  

You could just provide an unique_together like so:

你可以提供一个unique_together如下:

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.

如果没有设置,那么title/blog必须是唯一的,那么category的NULLs将发挥作用。

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

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

#1


18  

First create a new, empty migration file:

首先创建一个新的空迁移文件:

python manage.py makemigrations --empty yourappname

Then, for each index add an appropriate RunSQL line:

然后,为每个索引添加适当的RunSQL行:

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

Finally, run migrate.

最后,运行迁移。

#2


0  

You could just provide an unique_together like so:

你可以提供一个unique_together如下:

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.

如果没有设置,那么title/blog必须是唯一的,那么category的NULLs将发挥作用。

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

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