[英]Django Model Calculated field as Database level?
I have the simplified model below:我在下面有简化的 model:
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? django 有没有办法将属性字段计算为数据库级别? 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:根据 B. Okba 的回答,我对我的代码进行了一些调整,首先转换为 dataframe,然后调用总值:
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.但我仍然很好奇是否有更好/更有效的处理方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.