Django密钥违反了唯一约束

时间:2015-05-28 14:14:47

标签: python django django-models

我有一个奇怪的问题,就是生成相同的PK给我错误:

function toTimeCode(milliseconds:Number) : void 
{
    var se:Number=Math.floor(milliseconds/1000);
    var mi:Number=Math.floor(se/60);
    var ms:Number=Math.floor(milliseconds-1000*se);
    se=se-mi*60;
    // rest of translations remain intact
    var minutes:String = mi.toFixed(0);
    var seconds:String = se.toFixed(0);
    var miliseconds:String = String(ms/100);

    //add zero if neccecary, for example: 2:3.5 becomes 02:03.5
    minutes = (minutes.length != 2) ? '0'+minutes : minutes;
    seconds = (seconds.length != 2) ? '0'+seconds : seconds;
    //display elapsed time on in a textfield on stage
    timer_txt.text = minutes + ":" + seconds+"." + miliseconds;
}

这是我的模特:

django.db.utils.IntegrityError: duplicate key value violates unique constraint "Comment_pkey"
DETAIL:  Key (id)=(uxlt72XrRu-fm260qHo9Zg) already exists.

生成ID的函数:

class Comment(models.Model):

    id = models.CharField(primary_key=True, max_length=28, unique=True,
                          default="make_id()", editable=False)
    description = models.TextField(max_length=255)

我是如何得到错误的:

  

c = Comment.objects.create(description =" test")< ====工作

     

c2 = Comment.objects.create(description =" test2")< ===违反了唯一约束

那么为什么我的模型每次都不会生成新ID?同样的事情发生在测试而不仅仅是shell。

1 个答案:

答案 0 :(得分:5)

默认参数的正确用法是:default=make_id。因此,字段行将是:

id = models.CharField(primary_key=True, max_length=28, unique=True,
                      default=make_id, editable=False)