2010-05-23 5 views
3

내 모델에 다 대다 관계가 있으며 내 페이지 중 하나에서 재구성하려고합니다.Django에서 다 대 다 관계 재구성

내 사이트에 비디오가 있습니다. 각 동영상 페이지에 나는 그들이 비디오에 각 시간에 대한 링크가 그 비디오에 배우를 나열하기 위해 노력하고있어 여기에

(링크는 비디오의 부분으로 건너 뜁니다은) 그림


에게있어

플래시 비디오는 여기 여기

배우 ...

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

내가보기에 당신의 논리를 넣어 제안 것 이상 반복 함수가 템플릿이 아닙니다. 만약 내가 제대로 이해하고, 각 페이지에 당신은 비교적 간단한 일 actor.times을 통해 템플릿에 다음

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 

, 당신이 할 수있는 단지 루프를 만드는 하나 개의 비디오가 :

<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

내가이 일의 가장 장고 틱 방법은 "재편성"템플릿 태그를 사용하는 것입니다 생각 액터 모델 클래스의 사용자 정의 기능으로 시간 (비디오) 함수를 정의 :

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

그런 식으로 템플릿에서 원하는 것보다 더 많은 로직을 사용하지 않아도됩니다. BTW, 재 그룹 태그 here

을 읽을 수 있습니다.