这是一种类似IMDB的关系:我有一组视频,对于每个视频,视频中都有用户信用。像 -
这样的东西For Video 1:
User 1 - Director
User 2 - Writer
...etc...
以下是我的模型 -
class VideoInfo(models.Model):
title = models.CharField(max_length=256)
uploaded_by = models.ForeignKey('UserProfile')
credits = models.ManyToManyField('UserProfile', through='VideoCredit', blank=True, related_name='video_credits')
...
class VideoCredit(models.Model):
video = models.ForeignKey(VideoInfo)
profile = models.ForeignKey('UserProfile', blank=True, null=True)
name = models.CharField(max_length=100, blank=True)
position = models.ForeignKey(Position)
timestamp = models.DateTimeField(auto_now_add=True)
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
...
对于给定的用户,我想按位置分隔视频点数。像 -
这样的东西For User A:
DIRECTOR
- Video 1
- Video 2
WRITER
- Video 1
- Video 3
...etc...
我如何在模板中完成这样的事情 -
{% for position in positions %}
<b>{{position}}</b>
{% for video in profile.videoinfo_set.filter(position = position) %} # ??
{{video}}
{% endfor %}
{% endfor %}
或者,有没有更好的方法来完成我想要做的事情?谢谢。
答案 0 :(得分:2)
令人惊讶的是有多少人不了解regroup。
#in view
credits = profile.videocredit_set.select_related().order_by('position') # will sort by id, but you can sort any way you like
#in template
{% regroup credits by position as credits_regrouped %}
{% for credit in credits_regrouped %}
<b>{{ credit.grouper }}</b>
<ul>
{% for item in credit.list %}
<li>{{ item.video }}</li>
{% endfor %}
</ul>
{% endfor %}
答案 1 :(得分:1)
按位置订购您的视频信息并使用{{ifchanged}}
模板标记:
<强> ifchanged 强>
检查一个值是否从循环的最后一次迭代中发生了变化。
答案 2 :(得分:0)
以[(position1, [video1, video2, ...]), (position2,[...])]
-
list_of_credits =[]
for position in positions:
list_of_videos=[]
for video in profile.videocredit_set.filter(position=position):
list_of_videos.append(video)
list_of_credits.append((position,list_of_videos))
{% for item in list_of_credits %}
<p><b>{{item.0}}</b></p>
{% for video in item.1 %}
<p>{{video}}</p>
{% endfor %}
{% endfor %}