Returning Hex UUID as default value for Django mod

2020-07-27 04:22发布

问题:

I tried to create a model with identifier generated from uuid4. But what I want instead of regular uuid, I want identifier has hex uuid format (without "-"). Here is what I tried:

class Model(models.Model):

    identifier = models.CharField(max_length=32, primary_key=True, default=uuid.uuid4().hex, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.identifier

    class Meta:
        abstract = True

instead of returning unique id every time inherited class instantiated, it returns the same id because of uuid4(). I tried to change the default value from uuid.uuid4().hex to uuid.uuid4.hex but it seems the hex is not callable from uuid4 directly. So what is the possible way to produce default value for my identifier from uuid with hex format?

回答1:

You need to make it callable

default=lambda: uuid.uuid4().hex

UPDATE

As @ZulwiyozaPutra noted. Solution fails while migration, what i am totally forgot is that Django cannot serialize Lambdas.

Solution would be defining new function with desired behavior:

def hex_uuid():
    return uuid.uuid4().hex

and using this function as default argument as callable:

identifier = models.CharField(default=hex_uuid, ...)


回答2:

class Model(models.Model):

    identifier = models.CharField(max_length=32, primary_key=True, default=uuid.uuid4, editable=False)

if you use uuid.uuid4() the function will be executed on runserver, just give the signature and django will do the rest.