0

我有一家商店,这家商店有优惠如果您购买 5 件此商品清单,您将获得 3 美元的折扣,我试着写一个查询,

但没有用

o=order_products.objects.filter(order__id=1).values('product').annotate(Sum('qty'))
offers.objects.filter(products__id__in=o.values('product_id')).distinct(True)

现在我怎么能匹配这个项目列表的数量等于有这个折扣或倍数

例如,如果他买了 5 件,他将获得 3 美元的折扣,如果他买了 10 件,他将获得 6 美元的优惠等......

class product(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    price=models.FloatField()

class order(models.Model):
    id = models.AutoField(primary_key=True)
    order_date = models.DateTimeField(auto_now=True)

class order_products(models.Model):
    product=models.ForeignKey(product)
    qty=models.IntegerField()
    order=models.ForeignKey(order)

class offers(models.Model):
    id = models.AutoField(primary_key=True)
    products = models.ManyToManyField(product)
    qty = models.FloatField()
    discount_amount=models.FloatField()
4

1 回答 1

0

一种方法:

from collections import Counter

order = order_products.objects.filter(order__id=1).values('product__pk')
product_count = dict(Counter(order))

discounts = {}

for id,count in product_count.iteritems():
  offer = offers.objects.filter(products__pk=id,qty=count)
  if offer.count():
     discounts[id] = offer.discount_amount

for id,discount in discounts.iteritems():
   print '%d of %s discounted by %0.3f' % (product_count[id],product.objects.get(pk=id).name,discount)
于 2012-04-14T15:44:55.690 回答