2012-04-14 209 views
0

我有一家商店,這家商店有一個報價的報價 的 之一,如果你買了5個項目的這份名單,你會得到優惠3美元, 我試着寫一個查詢,Django的查詢集

但沒有奏效

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個,他將得到discoun牛逼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() 

回答

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)