访问模板中的多对多关系数据

时间:2014-10-21 07:24:30

标签: python django django-models django-templates django-views

我是django的新手并试图模仿OOP概念。

我有演员和电影的模特。电影与演员模特有多对多的关系。

url.py

from movies import views

url(r'^recent/$', views.recentlyadded, {'movieid': 1}),

models.py

from django.db import models

class Actor(models.Model):
    actorid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=250)
    sex = models.CharField(max_length=1)

class Movie(models.Model):
    movieid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=250)
    actor = models.ManyToManyField(Actor)

view.py

from movies.models import *

def recentlyadded(request, movieid):
    m = get_object_or_404(Movie, pk = movieid)
    return render_to_response('search_results.html', {'movies': m})

search_results.html

{% if movies %}
    {{movies.title}}
        <ul>{{ movies.actor_set.all.count }}
            {% for actor in movies.actor_set.all %}
                <li>{{actor.name}}</li>
            {%endfor%}
        </ul>
{% endif %}

输出

The Dark Knight 

我根本没有获得演员名单。

我应该使用中介模型吗?如果是的话,如果我必须将导演与电影模型联系起来,会发生什么?应该创建多少个中间模型?

请帮助解决问题。提前谢谢。

1 个答案:

答案 0 :(得分:1)

尝试直接访问movies.actor

{% if movies %}
    {{movies.title}}
    <ul>{{ movies.actor.all.count }}
        {% for actor in movies.actor.all %}
            <li>{{actor.name}}</li>
        {%endfor%}
    </ul>
{% endif %}