Home > Net >  Get data from django database model
Get data from django database model

Time:02-10

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

obj = PhoneNumberVerification.objects.get(phone_number=phone_number)

And I suggest changing phone_number field form TextField to PositiveBigIntegerField

  • Related