About Primary Keys of UUID Type

Don't set the default value for UUID primary keys, because it will be evaluated at initialization and you won't be able to easily check if an instance is already saved or not. Use the save() method instead to assign the value.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import uuid
from django.db import models

class MyModel(models.Model):
    uuid = models.UUIDField(primary_key=True, default=None, editable=False)
    # …
    def save(self, *args, **kwargs):
        if self.pk is None:
            self.pk = uuid.uuid4()
        super().save(*args, **kwargs)

This way you can check in your Python code or templates:

1
2
3
4
if instance.pk:
    print("Object has been saved.")
else:
    print("Object is new.")

Tips and Tricks Programming Architecture Django 4.2 Django 3.2 Django 2.2