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()替换成save(force_update)时,有时会出现一个
DatabaseError: Forced update did not affect any rows.
我看到有关于以下方法的讨论:
john = People.objects.filter(identifier="john").update(salary=10000)
但这并没有真正帮助我,因为我还需要更新外键,而不仅仅是People对象。你会怎么做呢?
1 个回答
0
这看起来是因为你不小心给了“People”表里的“identifier”字段设置了主键。主键就是用来唯一标识每一条记录的。如果你在使用phpmyadmin,去你的表里检查一下,确保“identifier”不是主键。你可以通过进入关系视图来移除这个主键。