Search code examples
djangodjango-modelsuuid

Refresh UUID on model object save


so I have a model and I am using a UUID field. I just simply want to change the UUID(refresh the UUID) to a new UUID every time a model object is saved.

import uuid
from django.db import models

class MyUUIDModel(models.Model):
    id = models.UUIDField(default=uuid.uuid4, unique=True)
    # other fields
    
    def save(self, *args, **kwargs):
        //refresh the uuid. what do i do here?
        super(MyUUIDModel, self).save(*args, **kwargs)


Solution

  • You'll have to call uuid.uuid4() on save, otherwise you're attempting to pass the function itself to the model as the value of the field. You can generate a new UUID every time you save the instance like this:

    class MyUUIDModel(models.Model):
        id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True)
    
        def save(self, *args, **kwargs):
            self.id = uuid.uuid4()
            super(MyUUIDModel, self).save(*args, **kwargs)