Danil Melnikov
Danil Melnikov

Reputation: 316

Django add id field to the model if I have primary key

I need create model that have uuid field set as primary key and id field:

class SomeModel(models.Model):
    id = models._________ ? increment=1 unique=true
    uuid = models.CharField(max_length=36, unique=True, default=uuid4, editable=False, primary_key=True)

Upvotes: 0

Views: 685

Answers (2)

Pulath Yaseen
Pulath Yaseen

Reputation: 415

From what I understand, you need the field id to be a primary key and also auto created. If that's it you just need to add

import uuid


class SampleModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ...

here You don't have to specify any uuid when saving/creating, it will be automatically generated.

Upvotes: 0

Samir Hinojosa
Samir Hinojosa

Reputation: 825

In this case you have to write your own auto-incrementing solution in Model save. Try with the following code

import uuid

class Example(TimeStampedAuthModel):
    uuid = models.UUIDField('uuid', primary_key=True, default=uuid.uuid4, editable=False)
    id = models.IntegerField('id', default=1, editable=False)
    name = models.CharField("Name", max_length=150)

    def save(self, *args, **kwargs):
        
        if self._state.adding:
            last_id = Example.objects.all().aggregate(largest=models.Max('id'))['largest']

            if last_id is not None:
                self.id = last_id + 1

        super(Example, self).save(*args, **kwargs)

Upvotes: 1

Related Questions