0

I have a django model, PhoneNumberVerification.

It has two columns: phone number, and code. I want to be able to get the code if I am given a phone number. Essentially, search the table for which row has the phone number as my phone number, and fetch the code for that given row.

I could write SQL for this, but I do not know how to execute that to fetch data in django models, and I was wondering if there was a better non-sql way to do this.

My model:

class PhoneNumberVerification(models.Model):
    phone_number = models.TextField(max_length = 20, blank = False, unique = True)
    code = models.CharField(max_length = 8, blank = False)

What I want:

from .models import PhoneNumberVerification

def get_code(phone_number):
    # do some stuff
    return code
Datajack
  • 88
  • 3
  • 16

2 Answers2

1
def get_code(phone_number):
  verification = PhoneNumberVerification.objects.get(phone_number=phone_number)
  return verification.code

Django's documentation has great tutorial for beginners. Writing your first Django app, part 2

Minh Dao
  • 827
  • 8
  • 21
  • Thank you very much! It works, and the tutorial is very good too! – Datajack Feb 09 '22 at 08:49
  • 1
    Yeah. That's why I like Django: written by python, easy to integrate with machine learning models, detailed tutorial and documentation. – Minh Dao Feb 09 '22 at 09:03
1

to get the object, you can simply use:

def get_code(phone_number):
   try:
        phone_number_verification = PhoneNumberVerification.objects.get(phone_numer=phone_number)
        code = phone_number_verification.code
        return code
    except PhoneNumberVerification.DoesNotExist:
        pass # django will raise exception in case if number does not exist

if you know there is only one object that matches your query, you can use the get(), which will return the object directly.

Otherwise, you can use filter(), more on that here

Blomex
  • 305
  • 2
  • 12