0

I am creating some music app. I have "Track" model, and I want to let user create playlist, that can contain multiple Tracks. My searching didn't help me to do it. (Also one Track can be used in multiple playlists, for example Track "XXX" can be used in playlist "YYY" and in playlist "ZZZ").

Here's models.py:

from django.db import models
from django.contrib.auth.models import User
from .validators import *

#Model that accutaly contains user's tracks/songs
class Track(models.Model):
    title = models.CharField(max_length=40, null=True)
    description = models.CharField(max_length=500, null=True)
    author = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    miniature = models.ImageField(upload_to='images/track', default="defaults/default.png", validators=[validate_miniature_file_extension])

    audio_or_video = models.FileField(upload_to='audio_and_video/', default="file_not_found", validators=[validate_track_file_extension])

#Model that contains playlists
class Playlist(models.Model):
    title = models.CharField(max_length=40, null=True)
    description = models.CharField(max_length=500, null=True)
    author = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    miniature = models.ImageField(upload_to='images/playlist', default="defaults/default.png", validators=[validate_miniature_file_extension])

    Tracks = models.ForeignKey(Track, default=None, on_delete=models.CASCADE) # I tried this, but it won't work at all because it can contain only one Track

1 Answer 1

2

1/ In Playlist class, the attributes should be in lowercase : tracks and not Tracks.

2/ Because a track can be related to many playlists and a playlist to many tracks, you need a ManyToManyField (instead a ForeignKey):

tracks = models.ManyToManyField(Track)

3/ Then you can add as many tracks as you want:

playlist.tracks.add(tracks1)
playlist.tracks.add(tracks2)
...

No need to use .save() method when adding tracks with .add()

References:

ForeignKey: https://docs.djangoproject.com/fr/2.1/ref/models/fields/#foreignkey

ManyToMany: https://docs.djangoproject.com/fr/2.1/ref/models/fields/#manytomanyfield

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.