2010-05-23 94 views
3

我在我的模型中擁有多對多的關係,我試圖在我的一個頁面上重新組織它。在Django中重組多對多關係

我的網站有視頻。在每個視頻的頁面我試圖列出了符合環節每次都在視頻的時間到視頻演員(該鏈接會跳轉到視頻的那部分)

這裏有一個例證


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

我塑造成時間的字典列出

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) 

而且在模板我掛繞在那,而不是在實際的模板運行查詢

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,你需要檢查語法。希望能幫助到你!

獎勵積分:定義一個時間(視頻)函數作爲演員模型類

1

我想這樣做的最Django的雜交方法是使用「重組」模板標籤的自定義函數:

{% 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 %} 

這樣你就可以避免在模板中使用比你想要的更多的邏輯。順便說一句,你可以閱讀重組標籤here