Django得到所有相关的选择,其中Event = Event.id

时间:2011-09-27 00:22:28

标签: python django django-models

我正在尝试使用Django创建我的第一个应用程序。我正在使用以下代码创建事件列表。

{% for Event in location_list %}                         
{{ Event.lat }}, {{ Event.long }},
html: "{{ Event.id }}",
}]
{% endfor %}

我需要编辑代码以便

{{ Event.id }}

变得类似

{{ Get all Choice in choice_list WHERE event IS Event.id }}

这样做的正确语法是什么?

Model.py

from django.db import models

class Event(models.Model):
    info = models.CharField(max_length=200)
    long = models.CharField(max_length=200)
    lat = models.CharField(max_length=200)

def __unicode__(self):
    return self.info

class Choice(models.Model):
    event = models.ForeignKey(Event)
    choice = models.CharField(max_length=200)
    link = models.CharField(max_length=200)

def __unicode__(self):
    return self.choice

views.py

def index(request):
location_list = Event.objects.all()
choice_list = Choice.objects.all()
t = loader.get_template('map/index.html')
c = Context({
            'location_list': location_list,
            'choice_list': choice_list,
            })
return HttpResponse(t.render(c))

更新

我已经取代了

{{ Event.id }}

{% for choice in event.choice_set.all %} {{ choice }} {% endfor %}

它不会打印任何事件。

1 个答案:

答案 0 :(得分:2)

看起来你正试图follow relationships backward

# In the shell
# fetch events from the db
>>> events = Event.objects.all()
>>> for event in events:
...     # fetch all the choices for this event
...     event_choices = event.choice_set.all() 
...     print event_choices

在模板中,不包括方法调用的括号。

{% for event in location_list %}                         
  {{ event.lat }}, {{ event.long }}
  <ul>
    {% for choice in event.choice_set.all %}
      <li>{{ choice }}</li>
    {% endfor %}
  </ul>
{% endfor %}

您可能希望在外键定义中定义related_name参数:

class Choice(models.Model):
    event = models.ForeignKey(Event, related_name="choices")

然后,您可以在视图中使用event.choices.all(),在模板中使用{% for choice in event.choices.all %}