开发者

Iterate over a category in template

This is an IMDB-like relationship: I have a set of videos, and for each video, there are users credited in the video. Something like --

For Video 1: 
User 1 - Director
User 2 - Writer
...etc...

The following are the models I have --

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)

c开发者_Go百科lass UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    ...

For a given user, I want to separate video credits by position. Something like --

For User A:

DIRECTOR
    - Video 1
    - Video 2
WRITER
    - Video 1
    - Video 3

...etc...

How would I accomplish something like this in the template --

{% for position in positions %}
    <b>{{position}}</b>
    {% for video in profile.videoinfo_set.filter(position = position) %} # ??
        {{video}}
    {% endfor %}
{% endfor %}

Or, is there a better way to accomplish what I'm trying to do? Thank you.


It's surpising how many people don't know about 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 %}


Order your videocredit by position and use the {{ifchanged}} template tag:

ifchanged

Check if a value has changed from the last iteration of a loop.


Pass a list of tuples in the form of [(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 %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜