Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorganizing many to many relationships in Django

I have a many to many relationship in my models and i'm trying to reorganize it on one of my pages.

My site has videos. On each video's page i'm trying to list the actors that are in that video with links to each time they are in the video(the links will skip to that part of the video)

Here's an illustration


Flash Video embedded here

Actors...

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

Here are the pertinent 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()

Here's what my Actor_Video table looks like, maybe it will be easier to see what im doing

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

i feel like i have to reorganize the info in my view, but i cant figure it out. It doesn't seem to be possible in the template using djangos orm. I've tried a couple things with creating dictionaries/lists but i've had no luck. Any help is appreciated. Thanks.

like image 530
Galen Avatar asked Jan 27 '26 15:01

Galen


1 Answers

I think the most Django-ish way of doing this would be using the "regroup" template tag:

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

That way you'd avoid having to use more logic than you want in your template. BTW, you can read on the regroup tag here

like image 89
dguaraglia Avatar answered Jan 29 '26 05:01

dguaraglia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!