[英]Reorganizing many to many relationships in 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的模板中似乎不可能。 我已經嘗試了一些創建字典/列表的東西,但我沒有運氣。 任何幫助表示贊賞。 謝謝。
我認為最簡單的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標簽
我將它制作成時間表的字典
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 )
在模板中,我循環使用它,而不是在實際模板中運行查詢
我建議將你的邏輯放在視圖函數而不是模板中。 如果我理解正確,在每個頁面上你只有一個視頻,這使事情變得相當簡單
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模型類的自定義功能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.