开发者

Django get all related Choices where Event=Event.id

开发者 https://www.devze.com 2023-04-08 02:03 出处:网络
I\'m trying to create my first application using Django. I\'m using the following code to create a list of events.

I'm trying to create my first application using Django. I'm using the following code to create a list of events.

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

I need to edit the code so that

{{ Event.id }}

Becomes something like

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

What is the proper syntax for doing this?

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

view开发者_运维百科s.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))

Update

I have replaced

{{ Event.id }}

with

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

It doesn't print any events.


It looks like you're trying to 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

In the template, you don't include the parenthesis for the method call.

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

You may want to define the related_name parameter in your foreign key definition:

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

Then you can use event.choices.all() in your views and {% for choice in event.choices.all %} in your templates.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号