我的模型中有很多关系,我试图在我的一个页面上重新组织它。
我的网站上有视频。在每个视频的页面上,我试图列出该视频中的演员,每次他们在视频中都有链接(链接将跳到视频的那一部分)
这是一个插图
此处嵌入Flash视频
...演员
Ted smith: 1:25, 5:30
jon jones: 5:00, 2:00
以下是我的模型的相关部分
class Video(models.Model):
actor = models.ManyToManyField( Actor, through='Actor_Video' )
# more stuff removed
class Actor_Video(models.Model):
actor = models.ForeignKey( Actor )
video = models.ForeignKey( Video)
time = models.IntegerField()
这是我的Actor_Video表的样子,也许更容易看到我在做什么
id actor_id video_id time (in seconds)
1 1 3 34
2 1 3 90
我觉得我必须在我的视图中重新组织信息,但我无法弄明白。在使用djangos orm的模板中似乎不可能。我已经尝试了一些创建字典/列表的东西,但我没有运气。任何帮助表示赞赏。感谢。
答案 0 :(得分:1)
我认为Django-ish最常用的方法是使用“regroup”模板标签:
{% regroup video.actor_video_set.all by actor as video_times %}
{% for actor_times in video_times %}
<li>{{ actor_times.grouper }}: # this will output the actor's name
{% for time in actor_times %}
<li>{{ time }}</li> # this will output the time
{% endfor %}
</li>
{% endfor %}
这样你就可以避免在模板中使用比你想要的更多的逻辑。顺便说一句,你可以阅读regroup标签here
答案 1 :(得分:0)
我把它塑造成时间表字典
actor_sets = data['video'].video_actor_set.all()
data['actors'] = {}
for actor_set in actor_sets:
if not data['actors'].has_key( actor_set.actor ):
data['actors'][actor_set.actor] = []
data['actors'][actor_set.actor].append( actor_set.time )
在模板中我循环使用该模板,而不是在实际模板中运行查询
答案 2 :(得分:0)
我建议将你的逻辑放在视图函数而不是模板中。如果我理解正确,在每个页面上你只有一个视频,这使事情变得相当简单
def video_view(request,video_id)
video = Video.objects.get(pk=video_id)
actors = Actor.objects.filter(video=video)
#now add a custom property to each actor called times
#which represents a sorted list of times they appear in this video
for actor in actors:
actor.times = [at.time for at in actor.actor_video_set.filter(video=video).order_by('time')] #check syntax here
然后在模板中,你可以循环遍历actor.times:
<ul>
{% for actor in video.actors.all.distinct %}
<li>{{ actor }}:
<ul>
{% for t in actor.times %} #this now returns only the times corresponding to this actor/video
<li><a href="?time={{ t.time }}">{{ t.time }}</a></li> #these are now sorted
NB - 在不使用IDE的情况下编写了所有代码,您需要检查语法。希望它有所帮助!
奖励积分:将时间(视频)功能定义为Actor模型类的自定义功能