1

有一个模型:

class DomainPosition(models.Model):
    domain   = models.ForeignKey(Domain)
    keyword  = models.ForeignKey(Keyword)
    date     = models.DateField()
    position = models.IntegerField()

    class Meta:
        ordering = ['domain', 'keyword']

如果对于每个域我想显示下一个表(表中的数字是位置值),如何获取模板的位置记录:

+----------+--------+--------+-------+--------
| keyword  | date1  | date2  | date3 | ...
+----------+--------+--------+-------+--------
| keyword1 |    2   |    6   |    7  |   ...
+----------+--------+--------+-------+--------
| keyword2 |    4   |   12   |    5  |   ...
+----------+--------+--------+-------+--------
| keyword3 |    6   |    3   |    9  |   ...
+----------+--------+--------+-------+--------

其中views.py

def show_domain_history(request, domain_name):
    domain = Domain.objects.filter(name__contains=domain_name)
    if not domain:
        return HttpResponseRedirect('/')
    else:
        # positions = ...
        variables = RequestContext(request, {
            'domain':    domain[0].name,
            'positions': positions,
        })
        return render_to_response('history.html', variables)
4

2 回答 2

1
def show_domain_history(request, domain_name):
    domain = Domain.objects.filter(name__contains=domain_name)
    if not domain:
        return HttpResponseRedirect('/')
    else:
        variables = {'domain': domain }
        return render_to_response('history.html', variables)

现在在模板中,您可以通过以下方式迭代:

{% for dom in domain %}

name: {{ dom.name }}

{% for item in dom.domainposition_set %} 

     date: item.date

     position: item.position
{% endfor %}

{% endfor %}
于 2010-08-20T12:05:31.920 回答
0

由于您有一个外键 from DomainPositionto Domain,您应该能够获得引用特定域的所有域位置的dom集合dom.domainposition_set.all()

然后,您可以通过迭代模板中的域位置列表来构建表。

于 2010-08-20T07:09:23.640 回答