0

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)
Danil Melnikov
  • 256
  • 1
  • 3
  • 11
  • 1
    What is your question? – Chymdy Mar 12 '21 at 06:24
  • 1
    Take a look at [UUIDField](https://docs.djangoproject.com/en/3.1/ref/models/fields/#uuidfield) and [AutoField](https://docs.djangoproject.com/en/3.1/ref/models/fields/#autofield) – Scratch'N'Purr Mar 12 '21 at 06:25
  • AutoField can be only set with primary_key – Danil Melnikov Mar 12 '21 at 06:33
  • @DanilMelnikov In that case, you'll have to write your own auto-incrementing solution with an IntegerField. See possible [solutions](https://stackoverflow.com/questions/41228034/django-non-primary-key-autofield) – Scratch'N'Purr Mar 12 '21 at 06:38
  • @DanilMelnikov: no, an `AutoField` can also be used without setting it as primary key, but it makes often not that much sense. – Willem Van Onsem Mar 12 '21 at 07:45
  • But I actually do not really see why you set the `UUID` as pk, and not just the `id` as pk, and simply generate a uuid each time. What is the functional difference between the two? – Willem Van Onsem Mar 12 '21 at 07:50
  • 1
    @WillemVanOnsem no an `AutoField` actually must be a primary key check [the source code](https://github.com/django/django/blob/551b0f94bf62c81d9ff9d5f7e261bcd2a594a4d1/django/db/models/fields/__init__.py#L2467) of `AutoFieldMixin` – Abdul Aziz Barkat Mar 12 '21 at 09:06

2 Answers2

1

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)
Samir Hinojosa
  • 825
  • 7
  • 24
0

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.

Pulath Yaseen
  • 395
  • 1
  • 3
  • 14