2012-11-16 24 views
0

我正在嘗試創建允許用戶將項目保存到播放列表的功能,並且用戶可以有多個播放列表。每個項目也可以保存到多個播放列表。代表這些數據的最佳方式是什麼?多個表與外鍵連接它們或只是一個平板表?什麼是最有效的結構來保存我的數據庫中的數據?

多個表

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) 

回答

1

有實體之間的兩個主要關係是:

  • 播放列表 - >用戶,多對一
  • 視頻 - > PlayList,很多很多

基於上述,你應該在這樣的方式安排您的數據:

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)] 
相關問題