Django - 更新模型对象

时间:2014-04-17 16:14:00

标签: python django

我没有找到一个简单的答案,所以我在这里。

以下是我的模型的简化:

class People(models.Model):
    identifier = models.CharField(max_length=255, primary_key = True)
    name = models.CharField(max_length=255)
    house = model.ForeignKey(House)
    salary = model.IntegerField()

class House(models.Model):
    id = models.CharField(max_length=255, primary_key = True)
    color = models.CharField(max_length=255)

我需要更新一个人的信息。例如,让我们说约翰有很高的收入,可以用紫色而不是黄色来画他的房子。我希望能够做到这样的事情:

 john = People.objects.get(identifier="john")
 john.salary = 10000
 john.house.color = "purple"
 john.house.save()
 john.save()

我想知道Django做什么的方式是什么。现在,我遇到了一些像

这样的错误
john.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 546, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 650, in save_base
result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 215, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1661, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 937, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 41, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 56, in execute
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 54, in execute
return self.cursor.execute(query, args)
IntegrityError: duplicate key value violates unique constraint "people_pkey"
DETAIL:  Key (identifier)=("John") already exists.

当我用save(force_update)替换save()时,我有时会得到一个

DatabaseError: Forced update did not affect any rows.

我读了一些关于以下方法的内容:

john = People.objects.filter(identifier="john").update(salary=10000)

但它并没有真正起作用,因为我还需要更新外键而不仅仅是People对象。 你会做什么?

1 个答案:

答案 0 :(得分:0)

这似乎是因为您手动/意外地为People表中的'identifier'字段指定了主索引。如果您使用phpmyadmin转到您的表并确保标识符不是主键。您可以转到关系视图来删除主索引。