Python Forum
Querying Django model db - from Jose Portilla’s Udemy course
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Querying Django model db - from Jose Portilla’s Udemy course
#1
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]: 
Reply
#2
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.
Reply
#3
#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())
Larz60+ write Aug-09-2022, 10:22 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Django: View is unable to find attributes of database model pythonpaul32 0 537 Dec-07-2023, 06:38 PM
Last Post: pythonpaul32
Photo After using models.Model on my class Im getting 'ImproperlyConfigured' error Django khavro 1 2,200 Apr-05-2021, 03:11 PM
Last Post: SheeppOSU
  [Django]calculate value in model smabubakkar 0 1,678 Apr-15-2020, 03:40 PM
Last Post: smabubakkar
  Django: How to automatically substitute a variable in the admin page at Django 1.11? m0ntecr1st0 3 3,337 Jun-30-2019, 12:21 AM
Last Post: scidam
  Need your help to fix my database relationship in Django model PrateekG 0 2,676 Jul-02-2018, 11:08 AM
Last Post: PrateekG
  Django not saving model in management command F2Andy 1 3,278 Jun-02-2018, 03:17 PM
Last Post: F2Andy
  Django model.py model.foreignkey() HenryJ 1 3,235 Feb-09-2018, 04:21 AM
Last Post: DocSeussMan
  How do I make a Django model from a tab-delimited data file? newbietostuff 0 2,532 Jan-09-2018, 02:44 AM
Last Post: newbietostuff
  Django field model for HTML parser? Drone4four 0 4,157 Nov-15-2017, 02:43 AM
Last Post: Drone4four

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020