如何为Django模型生成HASH [英] How to generate HASH for Django model

查看:201
本文介绍了如何为Django模型生成HASH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的10位Django模型生成唯一的HASH值,我尝试了这些方法,但出现此错误

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

这是我尝试过的内容:

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)

我也尝试过这种方法:

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

我有一个脚本,每次运行时都会将数据插入此模型我上面提到的错误脚本..是否还有其他方法可以执行..我想将唯一的哈希值存储到列 hash_1,hash_2,hash_3 中。

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.

推荐答案

不要在您的字段中调用 _createHash()函数,而只是将引用传递给模型中的可调用对象,例如

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)

正如Lennart Regebro在他的回答中提到的,每次您将获得相同的值您尝试启动服务器。

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

Django文档这样说:


Field.default

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.

这篇关于如何为Django模型生成HASH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆