Q:

Django super save and #1062 duplicate entry for key "PRIMARY"

Following is my model,
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()

And when I do save, this error was raised.
obj = Problem(payer=payer, status="QI",user_data_json=user_data)
obj.save(int(1))

The following is my save method,
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)

I am apologizing if this is a stupid error as I am still new to Django. And so appreciate if you willing take time and solve this for my purpose.

A:

You should call super just once at the end of code because self.id is always False
in insert mode. so always super function called twice.
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)

