开发者

How to generate random numbers in django

开发者 https://www.devze.com 2023-03-13 06:01 出处:网络
I want to generate automatic random numbers in a blank field while saving it in django. EDIT The random numbers mus开发者_如何转开发t be unique.EDIT: Changed solution to make random number unique

I want to generate automatic random numbers in a blank field while saving it in django.


EDIT

The random numbers mus开发者_如何转开发t be unique.


EDIT: Changed solution to make random number unique and to use Django's make_random_password

function. Note the below assumes you are storing the random number in a field called

temp_password in a model UserProfile that is an extension of the User model.

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')

Also note that you can store the random code as a combination of letters and numbers as well. The

default value for allowed_chars is a string of letters and numbers minus a few that tend to cause

confusion among users (1, l, etc.)

More about Django's make_random_password function: https://docs.djangoproject.com/en/dev/topics/auth/#manager-functions

OLD:

import random

n = random.randint(a,b) # returns a random integer

in the example above a <= n <= b

Many more types of random numbers in the random class: http://docs.python.org/library/random.html


It is more a python thing than a django thing.

You can find all the information about Random class here

Good luck!


Simply, I made a random number by random.randint in python. then as i need uniqe number, so i query this number to database, if this number is already exist, then i make again random by while loop.

random_num =  random.randint(2345678909800, 9923456789000)

uniqe_confirm = Order.objects.filter(order_id=random_num)

while uniqe_confirm:
    random_num =  random.randint(2345678909800, 9923456789000)
    if not Order.objects.filter(order_id=random_num):
        break
    
0

精彩评论

暂无评论...
验证码 换一张
取 消