Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: making a custom PK auto-increment?

Tags:

django

I've been using custom primary keys for a model in Django. (This was because I was importing values into the database and they already had ID's attached, and it made sense to preserve the existing values.)

class Transaction(models.Model):
    id = models.IntegerField(primary_key=True)
    transaction_type = models.IntegerField(choices=TRANSACTION_TYPES)
    date_added = models.DateTimeField(auto_now_add=True)

However, now I want to add new instances of the model to the database, and I'd like to autogenerate a unique primary key. But if I don't specify the ID at the time of creating the instance, I get an error:

t = Transaction(transaction_type=0)
t.save()

gives:

IntegrityError at /page
(1048, "Column 'id' cannot be null")

How can I autogenerate a unique ID to specify for new values, without having to alter the way I import the existing values?

UPDATE

I've written this custom method, which seems to work...

class Transaction(models.Model):
    def save(self, *args, **kwargs):
        if not self.id:
            i = Transaction.objects.all().order_by('-id')[0]
            self.id = i.id+1
        super(Transaction, self).save(*args, **kwargs) 
like image 963
AP257 Avatar asked Jan 06 '11 15:01

AP257


1 Answers

I've ended up using very similar piece of code, but have made it slightly more generic:

def save(self, *args, **kwargs):
    if self.id is None:
        self.id =  self.__class__.objects.all().order_by("-id")[0].id + 1
    super(self.__class__, self).save(*args, **kwargs)

it uses self.__class__ so you can just copy paste this code to any model class without changing anything.

like image 130
Zappatta Avatar answered Sep 20 '22 05:09

Zappatta