0

我正在尝试创建允许用户将项目保存到播放列表并且用户可以拥有多个播放列表的功能。每个项目也可以保存到多个播放列表中。表示这些数据的最佳方式是什么?带有外键链接的多个表还是只有 1 个平面表?

多个表

class Playlist(models.Model):
    playlist = models.CharField('Playlist', max_length = 2000, null=True, blank=True)
    def __unicode__(self):
        return self.playlist
    
class Video(models.Model):
    video_url = models.URLField('Link to video', max_length = 200, null=True, blank=True)
    video_tag = models.CharField('Video ID', max_length = 2000, null=True, blank=True)
    def __unicode__(self):
        return self.video_url

class UserPlaylist(models.Model):
    profile = models.ForeignKey(User)
    playlist = models.ForeignKey(Playlist)
    def __unicode__(self):
        return unicode(self.playlist)

class Videoplaylist(models.Model):
    video = models.ForeignKey(Video)
    playlist = models.ForeignKey(UserPlaylist)
    def __unicode__(self):
        return unicode(self.playlist)

1张桌子

class Everything(models.Model):
    profile = models.ForeignKey(User)
    playlist = models.CharField('Playlist', max_length = 2000, null=True, blank=True)
    platform = models.CharField('Platform', max_length = 2000, null=True, blank=True)
    video = models.CharField('VideoID', max_length = 2000, null=True, blank=True)
    def __unicode__(self):
        return u'%s %s %s %s' % (self.profile, self.playlist, self.platform, self.video)
4

1 回答 1

1

实体之间有两种主要关系:

  • 播放列表 --> 用户,多对一
  • 视频 --> 播放列表,多对多

基于上述,您应该以如下方式排列数据:

class User():
    name = CharField()
    # other user info

class Video():
    name = CharField()
    # othter video info

class Playlist():
    user = ForeigenKey(User)
    name = CharField()

class PlaylistVideo():
    plist = ForeigenKey(Playlist)
    video = ForeigenKey(Video)

# When a user adds a video to one of his playlist
def add_video_to_playlist(user_name, playlist_name, video_name)
    user = User.objects.get(name=user_name)
    plist = Playlist.objects.get(user=user, name=playlist_name)

    video = Video.objects.get(name=video_name)
    plv = PlaylistVideo(plist=plist,video=video)
    plv.save()

# To get the content of a user's some playlist:
def get_playlist_content(user_name, playlist_names):
    user = User.objects.get(name=user_name)
    plist = Playlist.objects.get(user=user, name=playlist_name)

    return [plv.video for plv in PlaylistVideo.objects.filter(plist=plist)]
于 2012-11-16T05:25:33.843 回答