简体   繁体   中英

Python and django, how to extract data from the queryset

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?

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

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM