Generate unique hashes for django models
        Posted  
        
            by becomingGuru
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by becomingGuru
        
        
        
        Published on 2010-03-25T22:29:11Z
        Indexed on 
            2010/03/25
            22:33 UTC
        
        
        Read the original article
        Hit count: 821
        
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
from base64 import urlsafe_b64encode
def set_unique_random_value(model_object,field_name='hash_uuid',length=5,use_sha=True,urlencode=False):
    while 1:
        uuid_number = str(random.random())[2:]
        uuid = hashlib.sha256(uuid_number).hexdigest() if use_sha else uuid_number
        uuid = uuid[:length]
        if urlencode:
            uuid = urlsafe_b64encode(uuid)[:-1]
        hash_id_dict = {field_name:uuid}
        try:
            model_object.__class__.objects.get(**hash_id_dict)
        except model_object.__class__.DoesNotExist:
            setattr(model_object,field_name,uuid)
            return
I'm seeking feedback, how else could I do it? How can I improve it? What is good bad and ugly about it?
© Stack Overflow or respective owner