'Get data from django database model
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 1:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Blomex |
