How to generate random numbers in django

后端 未结 3 1841
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
        
    

提交回复
热议问题