django模型中的增量计数和计算 [英] incremental count and calculation in django model

查看:110
本文介绍了django模型中的增量计数和计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的模型是这样的:

  class Publisher(models.Model):
name = models .CharField(max_length = 30)
code = models.SmallIntegerField(unique = True)

class Book(models.Model):
date = models.DateField(auto_now_add = True )
publisher = models.ForeignKey(Publisher)
hardback = models.BooleanField()
large_print = models.BooleanField()

对于给定的日期范围,我希望能够输出一个CSV,每个发布者的总书数和每个布尔字段的百分比。



例如:

 发行商代码Total%hardback%large_print:

123 120 32 10



(a)到目前为止,我正在制作一个视图,生成一个查询器,每个发布者的总书数

  totalset = Publisher.objects.all()
d1 = dict(totalset.annotate(total_books = Cou nt('publisher'))values_list('code','total_books'))

然后得到每个布尔字段的字典转换查询,例如

  d2 = dict(totalset.filter(book__hardback = True).annotate(hardc = Count('book__hardback'))values_list('code','hardc'))

然后获得一个新的字典,根据两组的交集计算百分比。

  d3 = {k:round(float(d2 [k])* 100 / d1 [k])for d1.viewkeys()& d2.viewkeys()} 

我是新来的,所以我觉得这是令人难以置信的令人费解的。是否有更直接的方式?



(b)如果可以在数据库中执行此操作(例如,使用某种模型属性),这是否更有效不如在数据库变大时在python中执行此操作?



非常感谢

解决方案>

我实际上最终使用了发布者模型的模型方法;如果有更好的方法,请让我知道!

  def get_percentage(self,d1,d2,choose):
kwargs = {'book__date__range':[d1,d2],'book__publisher':self}
kwargs2 = {'book__date__range':[d1,d2],'book__publisher':self,choose:True}
total_count = Publisher.objects.filter(** kwargs).count()
如果total_count == 0:
#otherwise perc返回ZeroDivisionError
返回total_count
count = Publisher .objects.filter(** kwargs2).count()
perc = round(float(count)* 100 / float(total_count))
return perc


Let's say my models are like this:

class Publisher(models.Model):      
    name = models.CharField(max_length=30)
    code = models.SmallIntegerField(unique=True)

class Book(models.Model):
    date = models.DateField(auto_now_add=True)
    publisher = models.ForeignKey(Publisher)
    hardback = models.BooleanField()
    large_print = models.BooleanField()

For a given date range, I want to be able to output a CSV which has total number of books per publisher, and percentage of each boolean field.

Eg:

Publisher-code Total %hardback %large_print:

123 120 32 10

etc

(a) So far I'm working on a view that generates a queryset with the total number of books per publisher

totalset = Publisher.objects.all()
d1 = dict(totalset.annotate(total_books=Count('publisher')).values_list('code','total_books'))

Then gets a dictionary-converted queryset of each boolean field e.g.

d2 = dict(totalset.filter(book__hardback=True).annotate(hardc=Count('book__hardback')).values_list('code','hardc'))

Then get a new dictionary that calculates the percentages based on the intersection of the two sets

d3 = {k: round(float(d2[k])*100/d1[k]) for k in d1.viewkeys() & d2.viewkeys()}

I'm new to all this, so I feel that this is incredibly convoluted. Is there a more straightforward way ??!

(b) If it's possible to do this in the database (e.g. with some sort of model property), is this more efficient than doing it in python as the database gets large ?

Thanks very much

解决方案

I actually ended up using a model method for the Publisher model; if there's a better way, please let me know !

def get_percentage(self, d1, d2, choose):
    kwargs = {'book__date__range':[d1,d2], 'book__publisher':self}
    kwargs2 = {'book__date__range':[d1,d2], 'book__publisher':self, choose:True} 
    total_count = Publisher.objects.filter(**kwargs).count()
    if total_count == 0:
        #otherwise perc returns a ZeroDivisionError
        return total_count
    count = Publisher.objects.filter(**kwargs2).count()
    perc = round(float(count) * 100 / float(total_count))
    return perc

这篇关于django模型中的增量计数和计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆