问题描述
我很少将模型实例添加到many2many字段时会得到这样的异常,例如:
I'm rarely getting such exception when adding model instance to many2many field, i.e.:
some_instance_A.my_m2m.add(some_instance_B)).
它的工作原理是99/100次。对我来说看起来很奇怪,就是这个破折号 - 主键是整数..
It works say 99/100 times. What looks strange to me, is that dash sign - as primary keys are integers..
模型字段定义如下:
my_m2m = ManyToManyField(B)
so这是最简单的M2M定义可能
so it's the simplest M2M definition possible
完全追溯(轻微编辑以保护隐私)):
Full traceback (with minor edits to protect privacy :)):
File "*******", line 278, in process_request
some_instance_A.my_m2m.add(some_instance_B)
File "/var/lib/python-support/python2.5/django/db/models/fields/related.py", line 490, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/var/lib/python-support/python2.5/django/db/models/fields/related.py", line 574, in _add_items
'%s_id' % target_field_name: obj_id,
File "/var/lib/python-support/python2.5/django/db/models/query.py", line 352, in create
obj.save(force_insert=True, using=self.db)
File "/var/lib/python-support/python2.5/django/db/models/base.py", line 435, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/var/lib/python-support/python2.5/django/db/models/base.py", line 528, in save_base
result = manager._insert(values, return_id=update_pk, using=using)
File "/var/lib/python-support/python2.5/django/db/models/manager.py", line 195, in _insert
return insert_query(self.model, values, **kwargs)
File "/var/lib/python-support/python2.5/django/db/models/query.py", line 1479, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/var/lib/python-support/python2.5/django/db/models/sql/compiler.py", line 783, in execute_sql
cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/var/lib/python-support/python2.5/django/db/models/sql/compiler.py", line 727, in execute_sql
cursor.execute(sql, params)
File "/var/lib/python-support/python2.5/django/db/backends/mysql/base.py", line 86, in execute
return self.cursor.execute(query, args)
File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line 166, in execute
self.errorhandler(self, exc, value)
File "/var/lib/python-support/python2.5/MySQLdb/connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
IntegrityError: (1062, "Duplicate entry '1830327-1792993' for key 'some_instance_A_id'")
推荐答案
您可以发布产生此结果的代码片段吗?
Can you post the code snippet that yields this result?
至少在Postgres上,如果您尝试在事务中保存两次实例,则可能会发生这种情况。
At least on Postgres this can happen if you try saving an instance twice inside a transaction.
这篇关于IntegrityError:(1062,“Duplicate entry”1830327-1792993“,用于密钥”some_instance_A_id“),但没有UNIQUE约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!