【问题标题】:Counting all order items for ecommerce site计算电子商务网站的所有订单商品
【发布时间】:2012-08-29 04:47:49
【问题描述】:

我正在建立一个食品配送网站。我目前已经全部设置好了,但是我正在构建管理页面来汇总每种食物的订单总量。

“位置”属性有 6 个可能的下车点。我有 3 个送货时间。我想计算每个交货时间/地点的所有单个食品。我不确定如何使用 django 来做到这一点。

最好的方法是什么?

我将实际的“订单”模型与“订单项”模型分开。

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)

订单项:

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)

【问题讨论】:

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


    【解决方案1】:

    试试annotate and Count:

    orders = orders.annotate(num_items=Count('orderitem_set'))
    
    for order in orders:
        print order.pk, order.num_items
    

    【讨论】:

      猜你喜欢
      • 2014-12-20
      • 1970-01-01
      • 2016-03-31
      • 2019-07-29
      • 2011-06-11
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多