我正在尝试创建允许用户将项目保存到播放列表的功能,并且用户可以拥有多个播放列表。每个项目也可以保存到多个播放列表中。表示此数据的最佳方式是什么?有多个表,外键可以链接它们,还是只有一个平面表?
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)
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)
答案 0 :(得分: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)]