计算电子商务网站的所有订单商品

时间:2012-08-29 04:47:49

标签: python django model one-to-many counter

我正在建立一个送餐网站。我目前已经完成了所有设置,但我正在建立管理页面,汇总每种食物的订单总量。

“location”属性有6个可能的下降点。我有3个送货下降时间。我想计算每个交货时间/地点的所有个别食品。我不知道如何使用django来做到这一点。

最好的方法是什么?

我从“orderitems”模型中分离了实际的“订单”模型。

class Order(models.Model):
    # each individual status 
    SUBMITTED = 1
    PROCESSED = 2
    SHIPPED = 3
    CANCELLED = 4

    # set of possible order statuses 
    ORDER_STATUSES = ((SUBMITTED,'Submitted'), (PROCESSED,'Processed'),
                        (SHIPPED,'Shipped'), (CANCELLED,'Cancelled'),)

    # order info
    date = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=ORDER_STATUSES, default=SUBMITTED)
    last_updated = models.DateTimeField(auto_now=True)
    transaction_id = models.CharField(max_length=20)


    #user info
    user = models.ForeignKey(User, null=True)
    full_name = models.CharField(max_length=20, blank=True)

    # contact info
    email = models.EmailField(max_length=50) 
    phone = models.CharField(max_length=20)

    # Drop point info
    location = models.CharField(max_length=50)

    #time of the drop info
    time = models.IntegerField()

    # billing information
    billing_name = models.CharField(max_length=50) 
    billing_address_1 = models.CharField(max_length=50) 
    billing_address_2 = models.CharField(max_length=50, blank=True) 
    billing_city = models.CharField(max_length=50)
    billing_state = models.CharField(max_length=2)
    billing_country = models.CharField(max_length=50)
    billing_zip = models.CharField(max_length=10)

    def __unicode__(self):
        return 'Order #' + str(self.id)

OrderItem的:

class OrderItem(models.Model):
    product = models.ForeignKey(Food)
    quantity = models.IntegerField(default=1)
    price = models.DecimalField(max_digits=7,decimal_places=2)
    order = models.ForeignKey(Order)

1 个答案:

答案 0 :(得分:0)

尝试annotate and Count

orders = orders.annotate(num_items=Count('orderitem_set'))

for order in orders:
    print order.pk, order.num_items