使用Django创建部分索引1.7 [英] Creating Partial Indexes with Django 1.7

查看:166
本文介绍了使用Django创建部分索引1.7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django 1.7的文档提到 RunSQL 类可用于在表上创建部分索引。我有一张表,我想要组合 title blog & 类别是唯一的。但是,如果没有提供类别,则标题和博客应该还是独一无二的。

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)

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

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;


推荐答案

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

First create a new, empty migration file:

python manage.py makemigrations --empty yourappname

然后,对于每个索引,添加一个适当的 RunSQL 行:

Then, for each index add an appropriate RunSQL line:

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

最后,运行 migrate

这篇关于使用Django创建部分索引1.7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆