相关疑难解决方法(0)

允许Django中的空值的唯一字段

我有模型Foo有字段栏.bar字段应该是唯一的,但允许空值,这意味着如果bar字段是null,我想允许多个记录,但如果不是,null则值必须是唯一的.

这是我的模型:

class Foo(models.Model):
    name = models.CharField(max_length=40)
    bar = models.CharField(max_length=40, unique=True, blank=True, null=True, default=None)
Run Code Online (Sandbox Code Playgroud)

这是表的相应SQL:

CREATE TABLE appl_foo
(
    id serial NOT NULL,
     "name" character varying(40) NOT NULL,
    bar character varying(40),
    CONSTRAINT appl_foo_pkey PRIMARY KEY (id),
    CONSTRAINT appl_foo_bar_key UNIQUE (bar)
)   
Run Code Online (Sandbox Code Playgroud)

当使用管理界面创建多个bar为空的foo对象时,它会给出一个错误:"Foo with this Bar已经存在."

但是当我插入数据库(PostgreSQL)时:

insert into appl_foo ("name", bar) values ('test1', null)
insert into appl_foo ("name", bar) values ('test2', null)
Run Code Online (Sandbox Code Playgroud)

这很好用,它允许我插入超过1条记录,条形为空,所以数据库允许我做我想要的,这只是Django模型的错误.有任何想法吗?

编辑

就DB而言,解决方案的可移植性不是问题,我们对Postgres感到满意.我已经尝试设置一个可调用的唯一,这是我的函数返回True/False为特定的bar值,它没有给出任何错误,但是如果它没有任何影响那么缝合.

到目前为止,我已经从bar属性中删除了唯一的说明符并处理了应用程序中的bar唯一性,但仍然在寻找更优雅的解决方案.有什么建议?

django orm django-models

121
推荐指数
7
解决办法
4万
查看次数

标签 统计

django ×1

django-models ×1

orm ×1