首页 > 解决方案 > 如何使用 Django 生成 6 位多个 OTP 并一次插入数据库

问题描述

我正在生成 6 位随机 OTP,views.py我只想使用单个 QuerySet 一次插入那些要插入到我的表中的许多 OTP。 这是我的代码:

主页.html

<form class="" action="" method="post">
  {% csrf_token %}
  <div class="" style="text-align: center:">
    Mobile : <input type="text" name="mobile" value="">
    <input type="submit" name="submit" value="Generate OTP">
  </div>
</form>

模型.py

class otpModel(models.Model):
    mobile = models.CharField(max_length=30, blank=False, null=True)
    otp = models.CharField(max_length=50, blank=False, null=True)

    def __str__(self):
        return self.mobile

视图.py

import random
from app_name.models import otpModel

def registerOTP(request):
   if request.method == 'POST':
       mobile = request.POST['mobile']

       for i in range(100):
          otp = random.randint(100000, 999999)
          otp = otpModel.objects.create(mobile=mobile, otp=otp)
          if otp:
             messages.info(request, 'OTP is saved!!!')
             return render(request, 'app_name/otp.html')
   else:
       return render(request, 'studentexams/otp.html')

每当我在 HTML 表单中输入手机号码时,表格中只会插入 1 个 OTP。是否有任何解决方案可以使用单个 QuerySet 一次插入多个 OTP

请给出完成此任务的代码片段

标签: pythonmysqldjango

解决方案


尝试以下

from itertools import islice
def registerOTP(request):
    if request.method == 'POST':
        mobile = request.POST['mobile']
        otps = []
        for i in range(100):
            otp = random.randint(100000, 999999)
            otp_obj = otpModel(mobile=mobile, otp=otp)
            otps.append(opt_obj)
        # I advise you to do the following in a celery task
        # Doing it in the request thread is a bad User experience
        batch_size = 50  # 50 is the batch size, you
        # can change it to any number you want based on your usecase
        while True:
            batch = list(islice(otps, batch_size))
            if not batch:
                break
            otpModel.objects.bulk_create(batch, batch_size)
            del otps[0:batch_size]
        if otp:
            messages.info(request, 'OTP is saved!!!')
            return render(request, 'app_name/otp.html')

    else:
        return render(request, 'studentexams/otp.html')

推荐阅读