'Subtract Year from an object in a Django Project
I'm trying to subtract year data from a model object created in a Django project. I would like to obtain a final value comparing a date in an object registered in my model with the value of the current year, 2022. Something like an anniversary date calculation for an ephemeris project.
Logic: Current Year - object with a 'year' value in a date field "1952";
Logic Example: 2022 - some_variable
Expected result = 70
My model:
class Person(models.Model):
dateborn= models.DateField()
I'm trying to use .dates() in the logic in my views.py to get the year:
from app.models import Person
persons = Person.objects.all()
dateborn = persons.dates('dateborn','year')
then I get a result:
<QuerySet [datetime.date(1935, 1, 1)]>
OK!
I'm struggling now to elaborate a logic to subtract the result of this QuerySet using only the 'YEAR' of the object. I know that if I use an INT I will not be able to perform the calculation.
I try:
#used
resultfinal = 2022 - dateborn
AND
#used
resultfinal = datetime.today().strftime('%d/%m') - dateborn
Then
#My expected end result would be something like this:
resultfinal = 2022 - 1935
I know I'm mixing things up, but I can't find a method of subtracting correctly. :(
I expect to use the final result of the subtraction calculation to print to my HTML template using jinja2 after specifying the 'resultfinal' variable in my context dictionary. In my HTML file I expect to use a for condition to get the values in a list:
{% for x in resultfinal %}
<p> Anniversary: {{x}} years </p> <!--Expected difference from the year registered in the database (-) the current year 2022-->
{% endfor %}
Can someone help me please? Thank you very much!
Solution 1:[1]
First of all, dateborn is a QuerySet as you showed, so use dateborn[0] to get the date object.
If you want the year, do dateborn[0].year, which will give you an integer of the year (1935) which you can subtract from.
resultfinal = datetime.date.today().year - dateborn[0].year
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 | figbar |
