如何在django中获得许多关联记录

时间:2016-12-26 10:03:56

标签: python django

我有一个事件表和另一个表event_performance_details,每个事件可以有多个表演,所以我必须找到属于特定事件的所有表演,同时从事件表中提取记录。

events = Event.objects.all().filter(event_start_to__gte=today, status=True, current_step=3).order_by('-id')[:3]
for event in events:
    # Here i have to get the records of event performances 

在event_performance_details表中,我使用event_id作为事件表记录的外键。

编辑:这是我的模板代码,我必须使用嵌套循环进行事件演出

{% for event in events %}
    <p class="date-para">
    {% with performances = event.event_performance_details_set.all() %}
        {% for performance in performances %}
            {{ performance.city }}
        {% endfor %}
    {% endwith %}
    </p>
{% endfor %}

1 个答案:

答案 0 :(得分:2)

你可以使用反向关系来检索每个事件的表现,如下所示:

events = Event.objects.all().filter(event_start_to__gte=today, status=True, current_step=3).order_by('-id')[:3]
for event in events:
    event.event_performance_details_set.all() # returns performances for the event

像Andrey Zarubin指出的那样编辑模板。应该是:

{% with performances = event.event_performance_details_set.all %}
    {% for performance in performances %}
        {{ performance.city }}
    {% endfor %}
{% endwith %}