回十六进制UUID作为Django模型charfield的默认值

回十六进制UUID作为Django模型charfield的默认值

本文介绍了返回十六进制UUID作为Django模型charfield的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用uuid4生成的标识符创建模型。但是我想要的不是常规的uuid,而是标识符具有十六进制的uuid格式(无-)。这是我尝试的方法:

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

而不是每次实例化继承的类时都返回唯一的ID,而是由于 uuid4()而返回相同的ID。 code>。我试图将默认值从 uuid.uuid4()。hex 更改为 uuid.uuid4.hex ,但似乎 hex 不能直接从 uuid4 调用。那么从十六进制格式的uuid中为我的标识符生成默认值的可能方法是什么?

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?

推荐答案


更新

为@ ZulwiyozaPutra指出。迁移时解决方案失败,我完全忘了Django无法序列化Lambda。

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, ...)

这篇关于返回十六进制UUID作为Django模型charfield的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:34