Django-更新主键charfield重复实例 [英] Django - updating primary key charfield duplicates instance

查看:203
本文介绍了Django-更新主键charfield重复实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用charfield作为主键的模型。
在创建实例(通过管理面板)时,一切都很好,我的清理方法也可以。但是,如果我回来更新myfield,不仅清理方法无法捕获非数字字符,而且整个实例也会重复。

I have a model with a charfield serving as primary key. While creating an instance (through admin panel) everything is fine and my clean method works ok too. But if I come back to update myfield than not only clean method fails to catch non-numeric characters, but the whole instance is duplicated. One with old myfield value and the new one with altered myfield.

# models.py
class Mymodel(models.Model):
    myfield = models.CharField(primary_key=True, max_length=10)
    ...
    def clean(self):
        if not re.match(r'[0-9]+', self.pesel):
            raise ValidationError('Digits only.', code='invalid')
        super(Mymodel, self).clean()

我该如何解决?我需要它成为主键,并且需要它是可编辑的。而且这种清洁的其他问题无法正常运行,我认为它可能已连接。我是Django 1.5.5

How can I fix this? I need it to be a primary key and I need it to be editable. And extra issue with this clean not functioning well, I think it may be connected. I'm Django 1.5.5

推荐答案


我的意思是通过django admin更新实例。更改myfield的值
并单击保存按钮不会更改实际实例
,而是创建(复制所有其他字段)新的实例。

I meant updating an instance through django admin. Changing the value of myfield and clicking save button doesn't change the actual instance but create (duplicating all the other fields) the new one.

这是django的工作原理,来自文档

This is how django works, from the documentation:


  • 如果对象的主键属性设置为一个值为 True 的值(即,除 None 以外的值或空字符串), Django执行 UPDATE

  • If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE.

如果未设置对象的主键属性或 UPDATE 没有更新任何内容,Django执行了 INSERT

If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.

您将陷入第二条。 django第一次尝试进行更新时,您的新主键值不存在;因此django将插入一条新记录。

You are getting caught in the second clause. The first time django attempts to do an update, your new primary key value doesn't exist; so django will insert a new record.

您是否需要将其作为主键或作为?通常,主键是唯一值;创建记录后(并且由于您具有链接的外键),请不要修改主键,否则您的关系将中断。实际上,如果您尝试这样做,大多数数据库都会引发错误。因为您将拥有指向不存在的键的记录。

Do you need to have it as a primary key or just as a key? Typically a primary key is a unique value; once a record is created (and since you have foreign keys, linked) - you do not modify the primary key otherwise your relationships will break. In fact, most databases will raise an error if you try to do this; as you will have records pointing to a key that doesn't exist.

这篇关于Django-更新主键charfield重复实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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