想找點什麼好像它應該是一個簡單的問題鬥爭的相關對象與註釋...參考在Django
基本上我有一些網站,對象計數發生在幾年:
例子:
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使用
查詢以上給了我只有最近幾年:
[{'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>
我曾嘗試以下(創建從上面後): B = Counts.objects.filter(year__in = A.values( '最近的'),site__site_id__in = p)的.annotate(site_code =最大( '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或2012年的所有值拉出。
又是什麼我要找的是最新的year. Max(count), Max(year)
最高計數 - 我敢肯定,在某種程度上扮演......
謝謝!
感謝你 - 實際上非常接近我需要的 - 這大部分返回我所需要的。我只需要更進一步,從site_name和site_code(從站點模型) – GrantRWHumphries
中將.select_related()添加到上述結果中,每個count對象都有相應的站點對象作爲屬性,site_name和site_code可通過模板中的內容獲得。所以A [0] .site.site_name會返回站點名稱。 select_related停止需要額外的數據庫命中,但該網站已經可用無論如何 – user5219763
這很好,謝謝user5219763 – GrantRWHumphries