Python Forum

Full Version: Querying Django model db - from Jose Portilla’s Udemy course
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I’m taking a Udemy course by Jose Portilla and I am learning how to query data in my Django shell.

To make things simple and straightforward, the instructor declared an age attribute for each person in the Patient model stored in the database.

But I am exploring a more accurate alternative. I’ve declared an alternate class attribute for the person’s date of birth (dob) and then I’ve added a class method called calculated_age() which returns a basic arithmetic operation which subtracts the person’s date of birth from the current date and time (now).

Here is my models.py:

from django.db import models
from datetime import datetime
from django.utils.timezone import now
from django.core.validators import MaxValueValidator, MinValueValidator


class Patient(models.Model):
   first_name = models.CharField(max_length=50)
   last_name = models.CharField(max_length=50)
   age = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(120)])
   heartrate = models.IntegerField(default=60,validators=[MinValueValidator(50), MaxValueValidator(180)])
   dob = models.DateTimeField(default=datetime(1957,6,6)) # Proper more precise date of birth to be calculated in method below
  
   def calculated_age(self):
       return datetime.date(now) - self.dob

   def __str__(self):
       return f"{self.first_name} {self.last_name} is {self.age} years old"

   def __repr__(self):
       return f"{self.first_name} {self.last_name} is {self.age} years old"
Does that look right? Am I missing anything above?

Next I am trying to get my Django shell to print the calculated_age() for any one of the entries in my database. Here is my shell input and output:

In [1]: from office.models import Patient

In [2]: obj = Patient

In [3]: Patient
Out[3]: office.models.Patient

In [4]: obj = Patient.objects.filter(first_name='Susan')

In [5]: obj
Out[15]: <QuerySet [Susan Smith is 33 years old]>
So that works so far. But how do I properly calculate the age of an instance of the Patient class in my Django shell?

Here is my best effort trying to calculate the precise age but unsuccessfully:

In [6]: obj.calculated_age
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [6], in <cell line: 1>()
----> 1 obj.calculated_age

AttributeError: 'QuerySet' object has no attribute 'calculated_age'

In [7]: obj.calculated_age()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [7], in <cell line: 1>()
----> 1 obj.calculated_age()

AttributeError: 'QuerySet' object has no attribute 'calculated_age'
In [8]: obj = Patient.objects.filter(first_name='Susan').calculated_age
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 obj = Patient.objects.filter(first_name='Susan').calculated_age

AttributeError: 'QuerySet' object has no attribute 'calculated_age'

In [9]: obj = Patient.objects.filter(first_name='Susan').calculated_age()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [9], in <cell line: 1>()
----> 1 obj = Patient.objects.filter(first_name='Susan').calculated_age()

AttributeError: 'QuerySet' object has no attribute 'calculated_age'

In [10]: 
Yes, all those methods give you back a QuerySet object. Looking at the API docs for QuerySet (https://docs.djangoproject.com/en/4.0/re...-querysets, which is linked to from https://docs.djangoproject.com/en/4.0/ref/models/), you might want to try calling .get() on those QuerySet objects to get the actual Patient object.
#Get Data By ID
from office.models import Patient
obj = Patient.objects.get(id=1)
print(obj.calculated_age())

#Filter Data By Any Field

from office.models import Patient
obj = Patient.objects.filter(name="your_name").first()
print(obj.calculated_age())