如何在django中生成随机数

Yes*_*nth 8 django-models

我想在空白字段中生成自动随机数,同时将其保存在django中.


编辑

随机数必须是唯一的.

rol*_*one 16

编辑:更改解决方案使随机数唯一,并使用Django的make_random_password

功能.请注意,下面假设您将随机数存储在一个名为的字段中

模型UserProfile中的temp_password,它是User模型的扩展.

random_number = User.objects.make_random_password(length=10, allowed_chars='123456789')

while User.objects.filter(userprofile__temp_password=random_number):
    random_number = User.objects.make_random_password(length=10, allowed_chars='123456789')
Run Code Online (Sandbox Code Playgroud)

另请注意,您也可以将随机代码存储为字母和数字的组合.该

allowed_chars的默认值是一个字母和数字的字符串减去往往会导致的一些字母和数字

用户之间的混淆(1,l等)

有关Django的make_random_password函数的更多信息:https://docs.djangoproject.com/en/dev/topics/auth/#manager-functions

旧:

import random

n = random.randint(a,b) # returns a random integer
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,a <= n <= b

随机类中有更多类型的随机数:http: //docs.python.org/library/random.html


jua*_*ith 2

它更像是 python 的东西而不是 django 的东西。

您可以在这里找到有关 Random 类的所有信息

祝你好运!