How to generate random numbers in django

后端 未结 3 1837
Happy的楠姐
Happy的楠姐 2021-02-05 23:38

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


EDIT

The random numbers must be unique.

相关标签:
3条回答
  • 2021-02-05 23:41

    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 讨论(0)
  • 2021-02-05 23:56

    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

    0 讨论(0)
  • 2021-02-06 00:06

    It is more a python thing than a django thing.

    You can find all the information about Random class here

    Good luck!

    0 讨论(0)
提交回复
热议问题