0

I want to generate an unique string in my django1.6 application. For that I want to concatenate the primary key (autofield) with the string. My code is

class Complaints(models.Model):
    gid     = models.AutoField(primary_key=True) 
    complaint_no    = models.CharField(max_length=50)       
    status      = models.IntegerField(default=0,blank=False,null=False)
    def __str__(self):
        return ('%s %s' % (self.gid, self.complaint_no))

    def save(self, force_insert=False, force_update=False):     
        self.complaint_no = '%s%d' % (self.complaint_no,self.gid)
        super(Complaints, self).save(force_insert, force_update)    
    class Meta:
        db_table = 'complaints'
        verbose_name = "complaints"     

But I got the error message as

TypeError at /callcentre/register/

%d format: a number is required, not NoneType

Please help me to solve this error!

Anju
  • 137
  • 2
  • 10

2 Answers2

1
  1. Create field id as charfield e.g.

string_id = models.CharField(max_length=100, default='file')

  1. Make a function that make string id when the model is saved. def save(self): new_id = self.id
    self.string_id = str(new_id) + '_dot' super(YourModelName, self).save()
Rieven
  • 9
  • 1
0

You need to call super() first.

As you can read in the documentation:

There’s no way to tell what the value of an ID will be before you call save(), because that value is calculated by your database, not by Django.

When you call super().save(), the database engine calculates the id (or gid in your case, but please reconsider using the provided id) and thus allows you to use it. Before that it is None.

You may check this topic as well.

Community
  • 1
  • 1
dsoosh
  • 693
  • 5
  • 9
  • Thank You @dsoosh , But if we put the super() first the complaint_no will not update with the corresponding id. for that I have to do one more save(). – Anju Jul 25 '14 at 05:30
  • @Anju: it would, if you had not overriden the `id` AutoField with your `gid` field (which definition is the same as id's, thus being redundant in this case), the superclass' `save()` method would've been invoked and the `id` value would have been calculated and available in your model's `save()` function. – dsoosh Jul 28 '14 at 09:06