Returning Hex UUID as default value for Django model charfield

徘徊边缘 提交于 2019-12-06 16:34:56

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!