views:

103

answers:

1

Here is the code I've written:

models.py:

class Name_overall(models.Model):
    rank = models.IntegerField()
    name = models.CharField(max_length=50)
    frequency = models.IntegerField()    
    def __unicode__(self):
        return self.name

class Name_state(models.Model):  
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    name_overall = models.ForeignKey(Name_overall, db_column='name')
    frequency = models.IntegerField()
    rank = models.IntegerField()
    state = models.CharField(max_length=2, choices=STATE_CHOICES)
    def __unicode__(self):
        return self.state

views.py:

def single_name(request, baby_name):
    baby_list = get_list_or_404(Name_overall, name=baby_name)
    return render_to_response('names/single_name.html', {'baby_list': baby_list})

single_name.html:

{{ baby_list.name_state_set.all }}

Nothing shows up in the single_name.html template. If I change it to {{ baby_list }}, there is an object there, but I am not able to access the Name_state class. I thought I should be able to have access to Name_state because of the foreign key. What am I missing?

+3  A: 

The baby_list context variable is a QuerySet. You need to iterate it and access the ForeignKey in the loop.

{% for item in baby_list %}
  {{item.name_state_set.all}}
  #iterate the name_state_set
  {% for obj in item.name_state_set.all %}
    {{obj}}
  {% endfor %}
{% endfor %}
czarchaic
Works like a charm. Thanks.
dhh9