Django如何为模型属性自动生成唯一的数字/字符串 [英] Django how to auto generate a unique number/string for a model attribute

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

问题描述

所以我一直试图在Django模型中生成10位唯一的随机数,而不用它作为我的主键.我的模型是

So i been trying to generate 10 digit unique random number in django model without making it my primary key. My model is

Class Transaction(models.Model):
      Referrence_Number = models.Charfield(max_lenght = 10, blank=True, editable=False, unique=True) 

我知道Django内部具有特殊功能,可以生成阅读文档后才知道的随机字符串.

I know that Django has special feature inside it to generate random string that i came to know after reading documentation.

from django.utils.crypto import get_random_string
get_random_string(10).lower()

但是我的问题是如何在我的Transcation_number实例的django事务模型中合并此get_random_string函数.我实际上是django的新手,无法弄清楚.

But my problem is how can i incorporate this get_random_string function inside my django transaction model in my Transcation_number Instance. I m actually new to django and cant able to figure it that out.

推荐答案

您可以将属性的默认值设置为一个函数,该函数生成所需的 Referrence_Number .只是不要在创建记录时设置 Referrence_Number

You can set a default on your attribute to a function that generates whatever Referrence_Number you'd like. Just don't set a Referrence_Number on record creation

例如,您的模型属性如下所示:

For example, your model attribute would look like this:

from utils import create_new_ref_number

Class Transaction(models.Model):
      Referrence_Number = models.Charfield(
           max_length = 10,
           blank=True,
           editable=False,
           unique=True,
           default=create_new_ref_number()
      )

在您的 utils.py 文件中,您将具有以下内容:

And in your utils.py file, you'd have something like this:

import random

def create_new_ref_number():
      return str(random.randint(1000000000, 9999999999))

虽然您可以简单地将 randint 函数放在 default 参数中,但您应该对其进行抽象处理,以便执行更多的操作,例如验证是否没有具有相同id的记录等

While you could simply throw the randint function in the default parameter, you should abstract it away so you can perform extra niceties like verify no record exists with that same id, etc.

这篇关于Django如何为模型属性自动生成唯一的数字/字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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