12

I am trying to generate unique HASH values for my Django models of 10 digit i have tried these methods but i am getting this error

return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: column hash_3 is not unique

Here what i have tried :

import os
import time
import hashlib
from os import path
from binascii import hexlify
from django.db import models
from django.contrib import admin
from django.core.files.storage import FileSystemStorage
#------------------------------------------------------------------------------ 

def _createHash():
    """This function generate 10 character long hash"""
    hash = hashlib.sha1()
    hash.update(str(time.time()))
    return  hash.hexdigest()[:-10]


class tags(models.Model):
    """ This is the tag model """

    seo_url1 = models.URLField()
    seo_url2 = models.URLField()
    seo_url3 = models.URLField()
    tagDescription = models.TextField()                 # Tag Description
    tag = models.CharField(max_length=200)              # Tag name
    tagSlug = models.CharField(max_length=400)          # Extra info can be added to the existing tag using this field
    updatedAt = models.DateTimeField(auto_now=True)     # Time at which tag is updated
    createdAt = models.DateTimeField(auto_now_add=True) # Time at which tag is created
    hash_1 = models.CharField(max_length=10,default=_createHash(),unique=True)
    hash_2 = models.CharField(max_length=10,default=_createHash(),unique=True)
    hash_3 = models.CharField(max_length=10,default=_createHash(),unique=True)

I have also tried this method:

def _createHash():
    """This function generate 10 character long hash"""
    return hexlify(os.urandom(5))

I have a script which inserts data into this model every time i run my script i got above mentioned error ..is there any other way of doing this..i want to store unique hash values into columns hash_1,hash_2,hash_3.

2 Answers 2

15

Don't call the _createHash() function in your field, but just pass the reference to the callable in your model, e.g.

hash_1 = models.CharField(max_length=10,default=_createHash,unique=True)

As Lennart Regebro mentioned in his answer, you'll get the same value for each time you start the server in your attempt.

The Django docs say this about it:

Field.default

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

Sign up to request clarification or add additional context in comments.

3 Comments

You are right out of curiosity but if i want to pass parameter to the method _createHash() then how do i do that.....
for instance i have a method def _generateSEOURL(pattern,StringToconcatenate): return pattern + StringToconcatenate and i want to pass seo_url1 = models.URLField(default=_generateSEOURL("discounts-in-",tag)) parameters like this ...to concatenate some string to every tag value then how do i do that...
You may have to just create a wrapper function which contains the parameters you would want to pass... def _createHashForModel(): return _createHash(10) and then default=_createHashForModel
5

_createHash() is called when you define the model, so you have the same default every time you create a new object.

You can look at creating the hash in the save() method of the model, that's probably the easiest.

1 Comment

Hi @Lennart_Regebro, how can we use it inside the save() method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.