Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django中带注释的引用相关对象_Python_Html_Django_Postgresql_Django Queryset - Fatal编程技术网

Python django中带注释的引用相关对象

Python django中带注释的引用相关对象,python,html,django,postgresql,django-queryset,Python,Html,Django,Postgresql,Django Queryset,与看似应该是一个简单问题的事情有点斗争 基本上,我有一些网站在几年内发生了物品计数: 例如: 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) 数据在时间上是不完整的(不规则的-一些站点数了几年..其他的没有。。此外,有时这些地方一年要数几次

与看似应该是一个简单问题的事情有点斗争

基本上,我有一些网站在几年内发生了物品计数:

例如:

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显示它

这是我的模特

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}]
但是-我希望它作为查询集(而不是ValuesQuerySet),因为我希望在HTML模板中引用它,如下所示:

<table>
{% for x in dat %}
    <tr><td>{{x.count|floatformat}}</td><td>{{x.year}}</tr>
{%endfor%}
</table>
{% for x in dat %}
    <tr ><td>{{ x.site.site_name }}</td><td>{{x.site.site_code}}</td><td>{{x.count|floatformat}}</td><td>{{x.year}}</td></tr>
{% endfor %}
换句话说,对于这两个站点,它都提取了年份=2010或2012的所有值

同样,我要寻找的是最近
一年的最高计数。马克斯(计数),马克斯(年份)
-我确信这在某种程度上起了作用


谢谢

使用
QuerySet
ValuesQuerySet
有两种解决方案

1。查询集

不建议用于大型
站点
计数
表,因为性能原因--对于每个站点,您将获得一个额外的查询,以获取最新的
计数对象(复杂性
O(N*M)
)。但是如果有少量的行,这是可以的。例如:

看法

模板

模板


{dat%中x的%s}
{{x.counts_set__count | floatformat}
{{x.counts\u set\u year}
{%endfor%}

希望这有帮助

如何按年份排序、计数并使用.distinct()只获取每个站点的第一条记录

A = Counts.objects.filter(site_id__in = p).order_by('site_id','-year','-count').distinct('site_id')
如果您需要相应的站点信息,可以在模板中访问

<table>
{% for x in dat %}
    <tr><td>{{x.count|floatformat}}</td><td>{{x.year}}</td><td>{{x.site.site_name}}</td></tr>
{%endfor%}
</table>

{dat%中x的%s}
{x.count | floatformat}{{x.year}{{x.site.site_name}
{%endfor%}
或者使用.values()指定要从视图中的每个模型中获取的值。结果也可在模板中使用。

编辑:

虽然下面的答案对我有用,但我还是很关心表现。。。 所以我重新基于user5219763哈希-现在更干净了

我已经修补过了,发现了这个作品

from itertools import chain

### First create an empty list to push querysets
qlist = []
### Iterate through each selected ID 
for x in p:
    ### Find the value for the latest year for each site id selected
    A = Site.objects.filter(site_id = x).aggregate(Max('counts__year'))['counts__year__max']
    if A:
        ### Find value of the highest count for year identified above for the selected site
        B = Counts.objects.filter(year = A, site__site_id=x).aggregate(Max('count'))['count__max']
        ### Now, resample the Site where the year is the max and count is max, then annotate the queryset
        ### with the values from year and count in the Counts table...
        C = Site.objects.filter(counts__year=A,counts__count=B).annotate(year = Max('counts__year'), count = Max('counts__count'))
        ### push this query to the list
        qlist.append(C)
    else:
        continue
            ### use itertools chain command to merge these into a single queryset
qs = list(chain.from_iterable(qlist))

现在我正在使用:

qs = Counts.objects.filter(site__site_id__in = p).order_by('site__site_id','-year','-count').distinct('site__site_id').select_related()
然后,在我的HTML中,我引用它如下:

<table>
{% for x in dat %}
    <tr><td>{{x.count|floatformat}}</td><td>{{x.year}}</tr>
{%endfor%}
</table>
{% for x in dat %}
    <tr ><td>{{ x.site.site_name }}</td><td>{{x.site.site_code}}</td><td>{{x.count|floatformat}}</td><td>{{x.year}}</td></tr>
{% endfor %}
{dat%中x的%
{x.site.site_name}{{x.site.site_code}{{x.count | floatformat}{{x.year}
{%endfor%}

谢谢大家

你好,艾伯特-谢谢你的建议。然而。您提供的ValuesQuerySet代码只是每年列出。“[{'counts\uuu year':None,'counts\uu count':None,'latest':None},{'counts\uu year':1994,'counts\uu count':807.0,'latest':1994}”等等……此外,这会创建一个ValuesQuerySet,它不能像您在模板中所描述的那样进行迭代。QuerySets可以工作,但ValuesQuerySets没有这么多。感谢这一点-实际上非常接近我所需要的-这将返回我所需要的大部分内容。我只需要进一步了解站点名称和站点代码(从站点模型)向上述添加。选择与站点相关的(),将导致每个计数对象都有其相应的站点对象作为属性,并且站点名称和站点代码可通过模板中的站点名称和站点代码获得。因此[0].site.site\u name将返回站点名称。选择\u相关停止需要额外的db命中,但该站点已可用。回答:好。但答案中的其他问题-这些问题不太可能被看到或回答,因为这不是这里的工作方式。如果您有新问题,请单击按钮提问。
from itertools import chain

### First create an empty list to push querysets
qlist = []
### Iterate through each selected ID 
for x in p:
    ### Find the value for the latest year for each site id selected
    A = Site.objects.filter(site_id = x).aggregate(Max('counts__year'))['counts__year__max']
    if A:
        ### Find value of the highest count for year identified above for the selected site
        B = Counts.objects.filter(year = A, site__site_id=x).aggregate(Max('count'))['count__max']
        ### Now, resample the Site where the year is the max and count is max, then annotate the queryset
        ### with the values from year and count in the Counts table...
        C = Site.objects.filter(counts__year=A,counts__count=B).annotate(year = Max('counts__year'), count = Max('counts__count'))
        ### push this query to the list
        qlist.append(C)
    else:
        continue
            ### use itertools chain command to merge these into a single queryset
qs = list(chain.from_iterable(qlist))
qs = Counts.objects.filter(site__site_id__in = p).order_by('site__site_id','-year','-count').distinct('site__site_id').select_related()
{% for x in dat %}
    <tr ><td>{{ x.site.site_name }}</td><td>{{x.site.site_code}}</td><td>{{x.count|floatformat}}</td><td>{{x.year}}</td></tr>
{% endfor %}