About the Default UUID Value

If you set the default value for the UUIDField, you cannot efficiently check if an object is new or if it has already been saved - the id will be set immediately when you create a model instance. But you can overcome this overwriting the save() method:

1
2
3
4
5
6
7
class MyModel(models.Model):
    id = models.UUIDField(primary_key=True, default=None)

    def save(self, *args, **kwargs):
        if not self.pk:
            self.pk = uuid.uuid4()
        super().save(*args, **kwargs)

Then you can check the state of the object in the template by the existence of pk:

1
<h1>{% if obj.pk %}{{ obj.title }}{% else %}New Object{% endif %}</h1>

Tips and Tricks Programming Development Django 4.2 Django 3.2 Django 2.2 Python 3