gerosalesc gerosalesc - 2 years ago 69
Python Question

Django easy retrival of items in a Many-to-many relationship model

I have a Many-to-many relationship with this couple of entities:

class Playlist(models.Model):
videos = models.ManyToManyField("Video")

class Video(models.Model):

I need a third model to replace the M2M relationship with a foreignKey to this couple of entities without the actual need to modify the way we access and query the playlist videos
, which would take us to a code refactoring hell. This is the third relationship:

class PlaylistVideos(models.Model):
playlist = models.ForeignKey('PlayList')
video = models.ForeignKey('Video')
new_field = models.IntegerField()
#... other stuff

Summarizing, I would like something like an alias attribute for easy access the videos of a particular playlist, any suggestions?

Answer Source

You can use a through table:

class Playlist(models.Model):
    videos = models.ManyToManyField("Video", through="PlaylistVideos")

This is documented here. You can still access the videos as playlist.videos but it will generate multiple queries and will thus be less efficient than before. This is discussed in How do I make Django ManyToMany 'through' queries more efficient?. You will need to decide if the extra queries will significantly impact your application. As discussed in the docs, you will not be able to add new videos to a playlist without using the PlaylistVideos model, since you will need to specify a value for new_field.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download