Get data from django database model

Advertisements

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

>Solution :

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

Leave a ReplyCancel reply