关于python:关键字“PRIMARY”的Django超级保存和#1062重复条目

Django super save and #1062 duplicate entry for key “PRIMARY”

以下是我的模特,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Problem(models.Model):
    pay_id = models.CharField(max_length=32, default=get_uuid_str)
    payer = models.ForeignKey(Profile, blank=True, null=True,
                              related_name='pay_out_list')
    payee = models.ForeignKey(Profile, blank=True, null=True,
                              related_name='pay_in_list')
    creation_datetime = models.DateTimeField(default=get_utc_now_with_tzinfo)
    expiry_datetime = models.DateTimeField(blank=True, null=True)
    status = models.CharField(max_length=2, default='I', choices=PAYMENT_STATUS)
    pay_type = models.CharField(max_length=2, default='C', choices=PAYMENT_TYPES)
    pay_symbol = models.CharField(max_length=10)
    pay_amt = models.FloatField(default=0.0)
    pay_qr_code = models.FileField(blank=True, null=True,
                                   upload_to=problem, storage=ca_public)
    return_url = models.CharField(blank=True, null=True, max_length=255)
    user_data_json = models.TextField(blank=True, null=True)
    objects = CAPayManager()

当我保存时,会出现此错误。

1
2
obj = Problem(payer=payer, status="QI",user_data_json=user_data)
obj.save(int(1))

以下是我的保存方法,

1
2
3
4
5
6
7
8
9
10
11
12
13
def save(self, *args, **kwargs):
    expiry_hrs = kwargs.pop('expiry_hrs', None)
    if not self.id:
        super(Problem, self).save(*args, **kwargs)
        self._create_save_qr_code()
        if expiry_hrs:
            try:
                expiry_hrs = int(expiry_hrs)
            except:
                expiry_hrs = -1
            if expiry_hrs > 0:
                self.expiry_datetime = self.creation_datetime + timedelta(hours=expiry_hrs)
    super(Problem, self).save(*args, **kwargs)

这是我的追溯FYI。

Traceback (most recent call last):
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/exception.py",
line 39, in inner
response = get_response(request)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/base.py",
line 249, in _legacy_get_response
response = self._get_response(request)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/base.py",
line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/base.py",
line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/views/decorators/csrf.py",
line 58, in wrapped_view
return view_func(*args, **kwargs)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/views/generic/base.py",
line 68, in view
return self.dispatch(request, *args, **kwargs)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/rest_framework/views.py",
line 466, in dispatch
response = self.handle_exception(exc)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/rest_framework/views.py",
line 463, in dispatch
response = handler(request, *args, **kwargs)
File"/Users/boonyao/Projects/copa/copa/api/internal/ico/views.py", line
44, in post
return problem_merchant_quick_pay(request, api_version, 'ico')
File"/Users/boonyao/Projects/copa/copa/api/internal/ico/problem/views.py",
line 42, in problem_merchant_quick_pay
return view_func(request, api_id)
File"/Users/boonyao/Projects/copa/copa/api/internal/ico/problem/views.py",
line 222, in problem_merchant_quick_pay_version_1_0
problem.save(int(1))
File"/Users/boonyao/Projects/copa/copa/problem/models.py", line 89, in save
super(CAPay, self).save(*args, **kwargs)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/base.py",
line 796, in save
force_update=force_update, update_fields=update_fields)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/base.py",
line 824, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/base.py",
line 908, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/base.py",
line 947, in _do_insert
using=using, raw=raw)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/manager.py",
line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/query.py",
line 1045, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/sql/compiler.py",
line 1054, in execute_sql
cursor.execute(sql, params)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/backends/utils.py",
line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/backends/utils.py",
line 64, in execute
return self.cursor.execute(sql, params)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/utils.py",
line 94, in exit
six.reraise(dj_exc_type, dj_exc_value, traceback)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/backends/utils.py",
line 64, in execute
return self.cursor.execute(sql, params)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/backends/mysql/base.py",
line 110, in execute
return self.cursor.execute(query, args)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/MySQLdb/cursors.py",
line 205, in execute
self.errorhandler(self, exc, value)
File"/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/MySQLdb/connections.py",
line 36, in defaulterrorhandler
raise errorclass, errorvalue
IntegrityError: (1062,"Duplicate entry '43' for key 'PRIMARY'")

我很抱歉,如果这是一个愚蠢的错误,因为我还是Django的新手。 如果你愿意花时间为我的目的解决这个问题,那就太欣赏了。


您应该在代码末尾调用super一次,因为self.id始终是False
在插入模式下。 所以总是super函数调用两次。

1
2
3
4
5
6
7
8
9
10
11
12
def save(self, *args, **kwargs):
expiry_hrs = kwargs.pop('expiry_hrs', None)
if not self.id:
    self._create_save_qr_code()
    if expiry_hrs:
        try:
            expiry_hrs = int(expiry_hrs)
        except:
            expiry_hrs = -1
        if expiry_hrs > 0:
            self.expiry_datetime = self.creation_datetime + timedelta(hours=expiry_hrs)
super(Problem, self).save(*args, **kwargs)