[英]Calculated field based on method inside Django model
How do I automatically populate a field in my PurchaseOrder model: 如何在我的PurchaseOrder模型中自动填充字段:
class PurchasedOrder(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField()
@property
def batch_cost(self):
return self.quantity * self.product.unit_price
def __str__(self):
return self.product.name
If I define it as a property, I won't be able to use this property to filter and stuff. 如果我将其定义为属性,则将无法使用该属性进行过滤和填充。 I want it to be a calculated field.
我希望它是一个计算字段。
I tried the following but it didn't work: 我尝试了以下操作,但没有成功:
def calculate_batch_cost(self):
return self.quantity * self.product.unit_price
batch_cost = models.FloatField(default=calculate_batch_cost)
I will appreciate your help <3 感谢您的帮助<3
You can .annotate(..)
[Django-doc] it in a QuerySet
, like: 您可以在
QuerySet
对其进行.annotate(..)
[Django-doc] ,例如:
from django.db.models import F
PurchasedOrder.objects.annotate(
batch_cost=F('product__unit_price') * F('quantity')
).filter(
batch_cost__gt=100 # An example of filtering
)
The PurchasedOrder
s from this queryset will have an attribute .batch_cost
that is the unit_price
of the product, times the quantity
. 该
PurchasedOrder
从这个查询集旨意有一个属性.batch_cost
那就是unit_price
产品,倍的quantity
。
We can then for example filter on that one. 然后,我们可以例如对该过滤器进行过滤。 For example in the above query, we will get all
PurchasedOrder
s with a batch_cost
that is greater than 100
. 例如,在上面的查询中,我们将获得
batch_cost
大于100
所有PurchasedOrder
。
If this field need to be specified and change anytime the object is created or updated, then you can add it inside the save funtion: 如果需要在创建或更新对象时指定此字段并进行更改,则可以将其添加到保存功能中:
def save(self, *args, **kwargs):
self.batch_cost = self.calculate_batch_cost()
super(PurchasedOrder, self).save(*args, **kwargs)
And of course, you need to add the field inside the model 当然,您需要在模型内添加字段
batch_cost = models.FloatField()
Then you can still use you calculate_batch_cost
function elsewhere in you code. 然后,您仍然可以在代码中的其他地方使用
calculate_batch_cost
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.