I have the simplified model below:
class Product(models.Model):
name = models.CharField(max_length=50)
price = models.FloatField()
class Invoice(models.Model):
product = models.ForeignKey(Product,on_delete=models.PROTECT)
quantity = models.FloatField()
@property
def total(self):
return self.quantity * self.product.price
I would like to be able to process data analysis on my Invoices data. If i load my queryset to a list, the total property is missing:
Invoice.object.all().values_list()
Is there a way with django to calculate the property field as a database level? So it would be easy to analyse from queryset (ideally i would like to load in dataframe)
Thanks for the tips !
a lazy method to do until you find better way
result = [{
"id": invoice.id,
"product": invoice.product,
"quantity": invoice.quantity,
"total": invoice.total,
} for invoice in Invoice.object.all()]
Based on B. Okba answer, I've slightly adapted in my code, converting first to a dataframe, and then calling for the total value:
from django_pandas.io import read_frame
df = read_frame(Invoice.objects.all())
df['total'] = df.apply(lambda x: Invoice.objects.get(id=x['id']).total,axis=1)
But i'm still curious if there is a nicer way/more efficient way to handle.
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.