Django超级保存和#1062键“ PRIMARY”的重复条目

时间:2018-08-14 03:31:36

标签: python mysql django

以下是我的模型,

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()

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

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

以下是我的保存方法,

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)

这是我的追溯信息。

  

回溯(最近通话最近):         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/exception.py”,   第39行,在内部           响应= get_response(请求)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/base.py”,   _legacy_get_response中的第249行           响应= self._get_response(请求)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/base.py”,   _get_response中的第187行           响应= self.process_exception_by_middleware(e,请求)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/base.py”,   _get_response中的第185行           响应= wraped_callback(请求,* callback_args,** callback_kwargs)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/views/decorators/csrf.py”,   第58行,在wrapped_view中           返回view_func(* args,** kwargs)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/views/generic/base.py”,   视线68           返回self.dispatch(request,* args,** kwargs)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/rest_framework/views.py”,   466行,正在派遣中           响应= self.handle_exception(exc)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/rest_framework/views.py”,   第463行,正在派遣中           响应=处理程序(请求,* args,** kwargs)         文件“ /Users/boonyao/Projects/copa/copa/api/internal/ico/views.py”,行   44,在后           返回issue_merchant_quick_pay(request,api_version,'ico')         文件“ /Users/boonyao/Projects/copa/copa/api/internal/ico/problem/views.py”,   第42行,在problem_merchant_quick_pay中           返回view_func(request,api_id)         文件“ /Users/boonyao/Projects/copa/copa/api/internal/ico/problem/views.py”,   第222行,在problem_merchant_quick_pay_version_1_0中           problem.save(int(1))         保存文件“ /Users/boonyao/Projects/copa/copa/problem/models.py”,第89行           超级(CAPay,self).save(* args,** kwargs)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/base.py”,   796行,保存中           force_update = force_update,update_fields = update_fields)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/base.py”,   save_base中的第824行           更新= self._save_table(原始,cls,force_insert,force_update,使用,update_fields)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/base.py”,   _save_table中的第908行           结果= self._do_insert(cls._base_manager,使用字段,update_pk,原始)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/base.py”,   _do_insert中的第947行           使用=使用,原始=原始)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/manager.py”,   第85行,在manager_method中           返回getattr(self.get_queryset(),name)(* args,** kwargs)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/query.py”,   _insert中的第1045行           返回query.get_compiler(using = using).execute_sql(return_id)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/models/sql/compiler.py”,   第1054行,在execute_sql中           cursor.execute(sql,params)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/backends/utils.py”,   第79行,在执行中           返回super(CursorDebugWrapper,self).execute(sql,params)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/backends/utils.py”,   执行中的第64行           返回self.cursor.execute(sql,params)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/utils.py”,   第94行,位于退出           6.reraise(dj_exc_type,dj_exc_value,回溯)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/backends/utils.py”,   执行中的第64行           返回self.cursor.execute(sql,params)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/db/backends/mysql/base.py”,   第110行,执行           返回self.cursor.execute(query,args)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/MySQLdb/cursors.py”,   第205行,在执行中           self.errorhandler(自我,排除,价值)         文件“ /Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/MySQLdb/connections.py”,   第36行,在defaultErrorhandler中           引发错误类,错误值       IntegrityError:(1062,“键“ PRIMARY”的条目重复“ 43”)”


如果这是一个愚蠢的错误,我深表歉意,因为我还是Django的新手。因此,如果您愿意抽出时间并为我的目的解决这个问题,那就谢谢。

1 个答案:

答案 0 :(得分:0)

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

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)