Reputation: 341
I have a question for you. I have the following class:
class StatoPatrimoniale(models.Model):
reference_date=models.DateField()
income=models.DecimalField()
debt=models.DecimalField()
After that I have named a new variable last_account_year
in th following manner:
now=datetime.datetime.now()
last_account_year=float(now.year)-1
Now I want to create a function that give me the possibility to extract the income
and debt
objects filtering them using the last_account_year
and the year in the reference_date
.
How could I get this result?
Upvotes: 0
Views: 383
Reputation: 4264
You should use the model date field lookup:
StatoPatrimoniale.objects.filter(reference_date__year=last_account_year)
And in a function encapsulating the logic and fixing it to zero if it doesn't exists:
def func(year):
queryset = StatoPatrimoniale.objects.filter(reference_date__year=year)
return queryset if queryset.exists() else 0
Upvotes: 1
Reputation: 691
You can use .filter() to filter your query and values_list() to get values: here is an exemple:
StatoPatrimoniale.objects.filter(reference_date__year=last_account_year).values_list('income', 'debt')
Upvotes: 0