django查询集

时间:2012-04-14 15:26:37

标签: django orm django-queryset

我有一家商店,这家商店有优惠 其中一个优惠 如果您购买此产品清单中的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()

1 个答案:

答案 0 :(得分: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)