如何设置随机整数作为Django CharField的默认值? [英] How to set a random integer as the default value for a Django CharField?

查看:133
本文介绍了如何设置随机整数作为Django CharField的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的models.py看起来像这样:

My models.py looks like this:

import random
random_string = str(random.randint(10000, 99999))

class Content(models.Model):
    ......
    unique_url = models.CharField(default = random_string)

当我在admin中添加内容时,将生成范围内的整数并将其作为默认值放入charfield中。从那里,我可以简单地向charfield添加更多单词。但是,当前设置的问题是,每次添加新文章时,整数都保持不变。我想生成并插入随机整数,因为我正在使用unique_url字段来基本上找到我的每个特定对象,并且我期望有很多内容,因此添加随机数通常可以确保每个内容都具有一个

When I add a content in admin, an integer in the range is generated and put into the charfield as its default value. From there, I can simple add more words to the charfield. However, the problem with my current set-up is that the integer remains the same every time I add a new article. I want to generate and insert the random integer as I am using the unique_url field to basically find each of my specific objects, and I am expecting a lot of content, so adding the random number will generally ensure that each content has a one of a kind unique_url.

因此,我正在寻找一个系统,该系统每次使用管理面板添加新内容时都会生成一个随机整数,并将其设置为默认值田野。

Therefore, I am looking for a system which generates a random integer everytime a new content is added using the admin panel, and puts it as the default of one the fields. Is such a thing even possible in Django?

推荐答案

这样您就可以一次生成一个随机数。您需要定义一个函数,例如:

This way you generate a random number once. You need to define a function such as:

def random_string():
    return str(random.randint(10000, 99999))

然后按现有方式定义模型,而无需 (),以便传递对函数本身的引用,而不是函数返回的值:

And then define your model as you already have, without () in order to pass a reference to the function itself rather a value returned by the function:

class Content(models.Model):
    ......
    unique_url = models.CharField(default = random_string)

这篇关于如何设置随机整数作为Django CharField的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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