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.
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:
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
Also by me
Django Messaging 🎅🏼
For Django-based social platforms.
Django Paddle Subscriptions 🎅🏼
For Django-based SaaS projects.
Django GDPR Cookie Consent 🎅🏼
For Django websites that use cookies.