I need to create a django ShortUUIDField that automatically generate the value when the entry is created:
Here's my code:
def generate_short_uuid():
string_uuid = str(uuid.uuid4())
return string_uuid.replace('-', '')[:12]
class ShortUUIDField(models.CharField):
def __init__(self, *args, **kwargs):
kwargs['default'] = generate_short_uuid
kwargs['editable'] = False
kwargs['unique'] = True
kwargs['blank'] = True
kwargs['null'] = True
kwargs['max_length'] = 12
super().__init__(*args, **kwargs)
def pre_save(self, model_instance, add):
if add:
while True:
try:
value = generate_short_uuid()
setattr(model_instance, self.attname, value)
return value
except IntegrityError as e:
if 'duplicate key' in str(e):
continue
raise
Here's the model that use the field:
class UserProfile(models.Model):
uuid = ShortUUIDField()
user = models.OneToOneField("users.User", on_delete=models.CASCADE, related_name="profile")
Here's the error that occurs when I try to create the entry:
django.db.utils.IntegrityError: null value in column "uuid" of relation "profiles_userprofile" violates not-null constraint
CodePudding user response:
The error you're seeing is because the uuid field in the UserProfile model is defined as a ShortUUIDField, which you've set to have a default value of the generate_short_uuid function. However, when you create a new UserProfile instance and don't explicitly set a value for the uuid field, the default value is None, which is not a valid value for the ShortUUIDField.
One way to fix this issue is to change the default value of the ShortUUIDField to generate_short_uuid() instead of the generate_short_uuid function. This way, when the field is instantiated, the default value will be the return value of the function (i.e. a new short UUID), rather than the function itself.
CodePudding user response:
you can use the ShortUUIDField from the shortuuidfield library to create a field that automatically generates a short universally unique identifier (UUID) for each instance of a model.
First, you'll need to install the shortuuidfield library using pip:
pip install django-shortuuidfield
from django.db import models
from shortuuidfield import ShortUUIDField
class MyModel(models.Model):
id = ShortUUIDField(primary_key=True)