Ordering members of a Many-to-Many-relationship

Let’s say I have model Track which represents a piece of music. A Track can be part of a collection called MusicAlbum via m2m-relationship. Let’s say the Track is “Run to the Hils” by Iron Maiden. It is part of MusicAlbum “The Number of the Beast” where it is Track 6 but it is also part of the MusicAlbum “Best of the Beast” where it is Track 4.
So having a Field TrackNumber on the model Track would be useless as the track number is context dependent. I’m thinking that I could use a JSON-field on the MusicAlbum model to store a dictionary with something like {‘track_number’: track.id} which stores the order of the tracks in the context of this album.
Is that a valid approach or is there something simpler?

I haven’t used it myself, but there is an example in the Django docs about this which is eerily similar to what you describe, only they talk about band members instead of band’s albums :slight_smile: The basic idea is that you add (link to) additional information in the table used for the many-to-many link. Or is this different from what you had in mind?

1 Like

That’s exactly what I need, thanks for pointing it out!

Something to notice: you cannot add a through option to a m2m-field and then migrate it. The through option must be there before the initial migration.