Generate unique hashes for django models

后端 未结 4 1390
感情败类
感情败类 2021-02-01 07:20

I want to use unique hashes for each model rather than ids.

I implemented the following function to use it across the board easily.

import random,hashlib         


        
4条回答
  •  伪装坚强ぢ
    2021-02-01 08:01

    The ugly:

    import random

    From the documentation:

    This module implements pseudo-random number generators for various distributions.

    If anything, please use os.urandom

    Return a string of n random bytes suitable for cryptographic use.

    This is how I use it in my models:

    import os
    from binascii import hexlify
    
    def _createId():
        return hexlify(os.urandom(16))
    
    class Book(models.Model):
        id_book = models.CharField(max_length=32, primary_key=True, default=_createId)
    

提交回复
热议问题