Django ORM查询:获取“有很多”关系对象

时间:2010-08-20 06:59:25

标签: python django django-models django-orm

有一个模型:

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)

2 个答案:

答案 0 :(得分: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 %}

答案 1 :(得分:0)

由于您拥有从DomainPositionDomain的外键,因此您应该能够获得使用dom引用特定域dom.domainposition_set.all()的所有域位置的集合

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