Reorganization of many, many relationships in Django

I have many different relationships in my models, and I'm trying to reorganize them on one of my pages.

There is a video on my site. On each video page, I try to list the participants who are in this video, with links each time they are in the video (links will skip this part of the video).

Here is an illustration


Flash video is included here.

Actors ...

Ted smith: 1:25, 5:30
jon jones: 5:00, 2:00

Here are the relevant parts of my models

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()

This is what my Actor_Video table looks like, it might be easier to see what im does

id     actor_id    video_id    time (in seconds)
1        1             3        34
2        1             3        90

I feel that I need to reorganize the information in my opinion, but I cannot figure it out. This is not possible in a template using djangos orm. I tried a couple of things with creating dictionaries / lists, but I was out of luck. Any help is appreciated. Thank.

+3
3

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

, Django-ish "":

{% 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 name
    {% for time in actor_times %}
        <li>{{ time }}</li> # this will output the time
    {% endfor %}
    </li>
{% endfor %}

, , . BTW,

+1

view, . , ,

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

0

Source: https://habr.com/ru/post/1746777/


All Articles