Home > Blockchain >  Django & PostgreSQL- Store Random Numbers in the database
Django & PostgreSQL- Store Random Numbers in the database

Time:12-18

In order to strengthen my basic knowledge in Django, I have decided to create something ther than a "to-do" list, I want to create a app that:

"will need to create a number of unique 6 digit codes and store in the database. This will be used to verify unique entries."

so my question is as follows:

  1. How can I quickly generate and store 50 random entries in my db
  2. How can I check if the user has a number that matches or not

What is the best way to approach this, I need to start thinking like a dev so I am looking for a bit of guidance and not the result, a nudge in the right direction, I have attached a mock up of the design where the user is requested to submit their "unique entry" and see if it matches to any one of them stored in the db

I am obviously reading the official django documentation too, but its not as straight forward for me to understand

Regards

Trevor

CodePudding user response:

You can follow these steps for an idea that will help you to solve your problem,

Step 1: Create a model to store unique 6-digit codes. For example:

from django.db import models

class UniqueCode(models.Model):
    code = models.CharField(max_length=6)

Step-2: To generate and store 50 random entries in your DB. You can use the random module to generate the codes and the UniqueCode model's save method to store them in the database.

import random

def generate_unique_codes():
    codes = []
    for i in range(50):
        code = ''.join(random.choices(string.digits, k=6))
        codes.append(Code(code=code))
    UniqueCode.objects.bulk_create(codes)

Step-3: To check if the user has a number that matches or not-

def check_code(code):
    return UniqueCode.objects.filter(code=code).exists()
  • Related