我如何设置一个表约束为“可延迟的初始延迟”?在Django模型中? [英] How can I set a table constraint "deferrable initially deferred" in django model?

查看:53
本文介绍了我如何设置一个表约束为“可延迟的初始延迟”?在Django模型中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PostgreSQL数据库为django中的表模型设置约束。

I am trying to set a constraint to a table model in django with a postgresql database.

我可以使用以下语句通过postgresql做到这一点:

I can do it via postgresql with this sentence:

ALTER TABLE public.mytable ADD CONSTRAINT "myconstraint" UNIQUE(field1, field2) DEFERRABLE INITIALLY DEFERRED;

但是我想通过Django模型实现。
阅读django官方文档时,我没有发现任何相关内容。

But I want to do it via django model. Reading the django official documentation I have not found anything related.

我需要这样的东西:

class Meta:
  unique_together = (('field1', 'field2',), DEFERRABLE INITIALLY DEFERRED)

是否可以做这样的事情?

Is it possible to do something like this?

推荐答案

Django

您可以使用自定义SQL来实现。在您的 models.py 中,添加以下内容:

You can do it with custom SQL. In your models.py, add this:

from django.db import connection
from django.db.models.signals import post_migrate

def after_migrate(sender, **kwargs):
    cursor = connection.cursor()
    cursor.execute('ALTER TABLE public.mytable ALTER CONSTRAINT '
                   'myconstraint DEFERRABLE INITIALLY DEFERRED')

post_migrate.connect(after_migrate)

尽管我过去做过这样的事情,但我发现多年来,我宁愿保持工作简单,独立于任何特定的RDBMS。例如,您确实要支持SQLite,因为它使开发变得如此容易。在设计上稍作更改,您通常可以摆脱这些东西。

Although I've done such things in the past, I've found that over the years I prefer to keep my work simpler and independent from any specific RDBMS. For example, you really want to support SQLite, because it makes development so much easier. With a little change in design you can often get rid of such stuff.

更新:我认为@fpghost的答案更好。我不知道我在想什么:-)

Update: I think @fpghost's answer is better. I don't know what I was thinking :-)

这篇关于我如何设置一个表约束为“可延迟的初始延迟”?在Django模型中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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