django在聚合后获取基础查询集项

时间:2015-09-29 12:38:52

标签: django

对于这些模型:

class Product(models.Model):
    code = models.IntegerField()


class Failures(models.Model):
    FAILURE_CHOICES = (
    ('SC', 'Screen'),
    ('BA', 'Battery'),
    ('BX', 'Box'),
    # etc, with 10+ choices
    )

    name = models.CharField(max_length=2, choices=FAILURE_CHOICES)


class Market(models.Model):
    MARKET_CHOICES = (
    ('ED', 'Education'),
    ('CO', 'Commercial'),
    # etc, with 10 choices
    )

    product = models.ForeignKey(Product)
    market = models.CharField(max_length=2,choices=MARKET_CHOICES)
    failures = models.ManyToManyField(Failures, blank=True)

我有这样的观点:

fails = ['SC','BA','BX',etc]

markets = [['ED'],['CO'],etc]

def fail_counter(fails):
    dictlist=[]
    for failure in fails:
    # dict1 = {failure:count}
        c = Failures(name=failure)
        d = str(c.get_name_display())
        kwargs = {d: (Count('failures'))}
        dict1 = total.filter(market__in=mark, failures__name=failure).aggregate(**kwargs)
        dictlist.append(dict1)
    return(dictlist)

fail_list=[]
for mark in markets:
    fail_list.append(fail_counter(fails))

然后将fail_list传递给一个模板,将其解压缩到一个表中, 所以我得到了例如

Market1(education)   Market2(commercial)    Market3(etc)
Failure   Count      Failure   Count        Failure   Count
Screen    0          Screen    0            Screen    0
Battery   0          Battery   1            Battery   0
Box       1          Box       0            Box       0
etc

转换任何计数的最佳方法是什么> 0进入类似管理员的链接 该计数中那些特定产品代码的更改列表?

0 个答案:

没有答案