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

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

问题描述

Django 1.7 的文档提到了RunSQL 类可用于在表上创建部分索引.我有一个表格,我想要 titleblog 和 & 的组合.category 是唯一的.但是,如果未提供类别,则 title 和博客应该仍然是独一无二的.

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;

推荐答案

Django 2.2 及更高版本

从 2.2 版开始,Django 支持声明性部分唯一索引 支持它们的数据库(PostgreSQL 和 SQLite).所以你可以这样做:

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 及更早版本

在旧版本中,您需要通过迁移来执行此操作.首先创建一个新的空迁移文件:

In older versions you need to do this with migrations. 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..."),
    migrations.RunSQL("CREATE UNIQUE INDEX..."),
]

最后,运行migrate.

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

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