Django聚合查询集 - 组合两个包含聚合的查询集的结果

时间:2014-01-30 20:45:39

标签: django django-models django-views django-queryset

我在django中有以下模型:

action = models.CharField("Action performed",max_length=200,db_index=True)
    date = models.DateField("Date when event occured",blank=True)
    time = models.TimeField("Time when event occured",blank=True)
    timestamp = models.DateTimeField("Timestamp when event occured",blank=True,null=True,db_index=True)
    username = models.ForeignKey(USER)
    computer = models.ForeignKey(COMPUTER)
    location = models.ForeignKey(LOCATION)

我希望将数据返回到HTML页面,该页面包含以下列:

COMPUTER NAME, COUNT(LOGON), COUNT(LOGOFF)

我正在使用

logOnOffData = LOGONOFF.objects.all()
computerBreakDown = logOnOffData.values("computer__computerName").annotate(Count("timestamp"))

这将生成数据库表中包含的每台计算机的出现次数。我可以轻松地为每个操作生成一个查询集,但无法看到如何将两个查询集的结果合并为一个。

1 个答案:

答案 0 :(得分:0)

过滤注释会很精彩,有些想法如下:

loging_logut = ( Computer
                 .objects
                 .all()
                 .annotate( longons = Count( action__action = 'logon' ) )
                 .annotate( longouts = Count( action__action = 'logout' ) )

但是django ORM上不允许使用这种语法。您可以在FILTERING ON ANNOTATIONS IN DJANGO帖子上了解相关信息。

在引用的文章中,您可以了解一些解决方法:例如writing your own sql code in extra field

如果性能不是问题,那么代码可读方法就是这样的字典:

{ 'john s computer': { 'n_logins': 100, 'n_logounts' :99 }, 
  'mathiew s computer': { 'n_logins': 80, 'n_logouts' :80 }, 
  ...
 }

要获取此词典,您可以单独注释登录和注销,然后加入它:

#logons = { 'john s computer': 100, 'mathiew s computer': 80, ... }
logons = dict(
               Computer
               .objects
               .filter( action__action = 'logon' )
               .annotate( longons = Count(  ) )
               .values_list( 'name', 'logons' )
         )

#logons = { 'john s computer': 99, 'mathiew s computer': 80, ... }
logouts = dict( ...

#joining dicsts
computers = {}
for computer in Computer.objects.all().values_list( 'name', flat = True):
    computers[computer]['n_logins'] = logons[computer]
    computers[computer]['n_logouts'] = logouts[computer]