这是我的用户订单模型
class Order(models.Model):
"""Order Models"""
first_name = models.CharField(
max_length=256,
blank=False,
verbose_name=_('Name'))
total_order_cost = models.DecimalField(
max_digits=10,
decimal_places=2,
default=21,
verbose_name=_('Total Order Cost'))
我的订购商品模型
class OrderItem(models.Model):
""" Ordered Item Model """
order = models.ForeignKey(Order,
verbose_name=_('Order'))
price = models.DecimalField(
max_digits=10,
decimal_places=2,
verbose_name=_('Price'))
quantity = models.PositiveIntegerField(
verbose_name=_('Quantity'))
total_price = models.DecimalField(
max_digits=10,
decimal_places=2,
verbose_name=_('Total Price'))
def get_cost(self):
return self.price * self.quantity
def save(self, *args, **kwargs):
self.total_price = self.get_cost()
super(OrderItem, self).save(*args, **kwargs)
字段total_price从get_cost获取值。如何使字段total_order_cost以相同的方式工作?我希望它从
获得价值def get_total_cost(self):
return sum(item.get_cost() for item in self.items.all())
我无法覆盖total_order_cost的方法保存,因为当我保存订单对象时 - 订购的商品尚不存在。 我的观点:
def make_order(request):
cart = Cart(request)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save() # here I save order object
for item in cart: # and here I save ordered items
OrderItem.objects.create(
order=order,
product=item.product,
price=item.product.price,
quantity=item.quantity)
cart.clear()
return HttpResponseRedirect('%s?status_message=%s'
% (reverse('get_cart'), _('Thank you for your order!')))
else:
form = OrderCreateForm()
return render(request, 'products/make_order.html', {
'form': form})
更新: 我明白我需要使用
@property
def total_order_cost(self):
return self.orderitem_set.aggregate(total=Sum(F('price') * F('quantity')))['total']
但我现在不知道如何使用它。我试过这样,但它不起作用:
class Order(models.Model):
total_order_cost = models.DecimalField( db_column='total_order_cost', max_digits=10, decimal_places=2, verbose_name=_('Total Order Cost'))
@property
def total_order_cost(self):
return self.orderitem_set.aggregate(total=Sum(F('price') * F('quantity')))['total']
答案 0 :(得分:3)
除非您遇到性能问题,否则为什么要存储派生数据?您可以从total_price
中删除OrderItem
字段,从total_order_cost
删除Order
字段,只需在需要时使用aggregation和F expressions进行查询。 something like this:
@property
def total_order_cost(self):
return self.orderitem_set.aggregate(total=Sum(F('price') * F('quantity')))['total']