Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 950
Shri Hegde Avatar asked May 22 '26 06:05

Shri Hegde


1 Answers

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)
like image 184
scissorhands Avatar answered May 24 '26 02:05

scissorhands