【发布时间】:2016-02-27 09:46:58
【问题描述】:
对似乎应该是一个简单的问题有点挣扎......
基本上,我有一些网站在几年内发生了对象计数:
例子:
site_id = Site1: (Year:2012,Count:133), (Year:2011, Count:150), (Year:2010, Count :110)
site_id = Site2: (Year:2010, Count:300), (Year:2010, Count 333)
数据在时间上是不完整的(不规则 - 有些网站被计算了几年......有些地方没有......)......而且,有时这些地方每年计算几次
我想要做的是获取每个站点的最新计数,如果有多个计数,我想获得最高计数.. 然后我想在 HTML 中显示它。
这是我的 MODELS.PY
class Counts(models.Model):
count_id = models.AutoField(primary_key=True)
site = models.ForeignKey('Site', blank=True, null=True)
year = models.IntegerField(blank=True, null=True)
count = models.FloatField(blank=True, null=True)
class Meta:
db_table = 'counts'
class Site(models.Model):
site_id = models.TextField(primary_key=True)
site_code = models.TextField(blank=True, null=True)
site_name = models.TextField(blank=True, null=True)
class Meta:
db_table = 'site'
这是我试图在 VIEWS.PY 中使用的查询
p = ['Site1','Site2'] ## Just for reference for the example... values come from a POST or a GET
A = Site.objects.filter(site_id__in = p).annotate(latest=Max('counts__year'))
context = RequestContext(request, {'dat':A})
template = loader.get_template('styles/searchResults.html')
return HttpResponse(template.render(context))
上面只给了我最近几年:
[{'site_id': u'Site1','latest': 2012}, {'site_id': u'Site2','latest': 2010}]
我想要的是:
[{'site_id': u'Site1','latest': 2012,'count':133}, {'site_id': u'Site2','latest': 2010,'count':333}]
但是 - 我希望它作为 QuerySet(而不是 ValuesQuerySet),因为我想在我的 HTML 模板中像这样引用它:
<table>
{% for x in dat %}
<tr><td>{{x.count|floatformat}}</td><td>{{x.year}}</tr>
{%endfor%}
</table>
我尝试了以下方法(在从上面创建 A 之后): B = Counts.objects.filter(year__in = A.values('latest'),site__site_id__in = p).annotate(site_code=Max('site__site_id'))
但这基本上会导致:
[{'site_id': u'Site1','latest': 2012,'count':133},{'site_id': u'Site1','latest': 2010,'count':110}, {'site_id': u'Site2','latest': 2010,'count':333},{'site_id': u'Site2','latest': 2010,'count':300}]
换句话说,它会提取两个站点的 YEAR = 2010 OR 2012 的所有值。
再次,我正在寻找的是最新 year. Max(count), Max(year) 的最高计数 - 我确信它会以某种方式发挥作用......
谢谢!
【问题讨论】:
标签: python html django postgresql django-queryset