Generate a random alphanumeric string as a primary key for a model

前端 未结 3 1988
Happy的楠姐
Happy的楠姐 2021-02-03 12:28

I would like a model to generate automatically a random alphanumeric string as its primary key when I create a new instance of it.

example:

from django.d         


        
3条回答
  •  渐次进展
    2021-02-03 12:52

    One of the simplest way to generate unique strings in python is to use uuid module. If you want to get alphanumeric output, you can simply use base64 encoding as well:

    import uuid
    import base64
    uuid = base64.b64encode(uuid.uuid4().bytes).replace('=', '')
    # sample value: 1Ctu77qhTaSSh5soJBJifg
    

    You can then put this code in the model's save method or define a custom model field using it.

提交回复
热议问题