如何设置django模型字段作为方法?

时间:2017-01-26 20:44:13

标签: python django django-models

这是我的用户订单模型

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

1 个答案:

答案 0 :(得分:3)

除非您遇到性能问题,否则为什么要存储派生数据?您可以从total_price中删除OrderItem字段,从total_order_cost删除Order字段,只需在需要时使用aggregationF expressions进行查询。 something like this

怎么样?
@property
def total_order_cost(self):
    return self.orderitem_set.aggregate(total=Sum(F('price') * F('quantity')))['total']