在Django模板中显示多对多的对象子集

时间:2011-04-19 05:17:09

标签: django many-to-many

这是我的模型的一部分:

class Character(models.Model):
    name = models.CharFied()

class Issue(models.Model):
    character = models.ManyToManyField(Character, related_name="appearances", blank=True, null=True)

我要做的是,当你去一个角色的页面时,它会显示角色所在的所有问题。

这就是我的观点设置方式:

def character(request, character_slug):
    character = get_object_or_404(Character, slug=character_slug)            
    return render_to_response('comics2/character_detail.html', {'character': character}, context_instance=RequestContext(request)

在模板中:

{{ character.name }}

作品

我试过了:

class CharactersView(ListView):
    context_object_name = "character_list"
    template_name = "comics2/character_detail.html"    
    def get_queryset(self):
        character = get_object_or_404(Character, slug=self.kwargs['character_slug'])
        return Issue.objects.filter(character=character)

但它不起作用..

但是我如何在模板中显示角色出现的所有问题?例如:

Character Name
Issue #1
Issue #2,
etc.

我觉得这很简单,但我没有得到它。我已经在互联网上寻找答案,但似乎无法找到有用的东西。所以,让我知道发生了什么,我更喜欢宝贝谈话,可能还有实际代码...谢谢!

1 个答案:

答案 0 :(得分:3)

您正在寻找following a relationship backwards

{% for issue in character.appearances.all %}
    {{ issue }}
{% endfor %}

因为您设置了相关名称,否则character.issue_set.all是默认名称。您还可以通过在视图中获取相关集来将问题添加到上下文中。

完整示例:

models.py

class Character(models.Model):
    name = models.CharField()
    slug = models.SlugField()

    def __unicode__(self):
        return "%s" % self.name

class Issue(models.Model):
    title = models.CharField()
    volume = models.IntegerField()
    character = models.ManyToManyField(Character, related_name="appearances", blank=True, null=True)

    def get_absolute_url(self):
        ...

views.py

def character(request, character_slug):
    character = get_object_or_404(Character, slug=character_slug)
    issues = character.appearances.all()

    context = {'character': character,
               'issues':issues,}                           

    return render_to_response('comics2/character_detail.html', 
        context_instance=RequestContext(request)

template.html

<h1>Appearances of {{ character }}<h1>
<table>
    <thead>
        <tr>
            <th>Title</th>
            <th>Volume</th>
        </tr>
    </thead>
    <tbody>
        {% for issue in issues %}
        <tr>
            <td><a href="{{ issue.get_absolute_url }}>{{ issue.title }}</a></td>
            <td>{{ issue.volume }}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>