【问题标题】:What is the proper way to structure models.py?构建models.py的正确方法是什么?
【发布时间】:2012-10-24 01:00:57
【问题描述】:

我正在尝试为我的 Django 应用构建正确的模型。我正在尝试构建一些东西,允许用户将 URL 保存到一个(或多个)与该用户相关的播放列表中。在我实现它之前,我想确保这是构建我的 models.py 的最佳方式。

class UserProfile(models.Model):
    user = models.ForeignKey(User, primary_key=True)    #what is the difference between ForeignKey and OneToOne?  Which one should I use?
    Playlist = models.CharField('Playlist', max_length = 2000)  #1 user should be able to have multiple playlists and the default playlist should be "Favorites"
    def __unicode__(self):
        return self.User

class Videos(models.Model):
    Video_url = models.URLField('Link to video', max_length = 200, null=True, blank=True)
    Playlist = models.ManyToManyField(Playlist) #this should connect to the playlists a user has.  A user should be able to save any video to any plalist, so perhaps this should be ManyToMany?
    def __unicode__(self):
        return self.Video_url

【问题讨论】:

标签: python django model


【解决方案1】:

哇。首先,对于 SO,这个问题可能过于“本地化”。反正。我会这样做:

class PlayList(models.Model):
    playlist = models.CharField(max_length=2000)

class UserProfile(models.Model):
    # do you want each `User` to only have one `UserProfile`? If so then OneToOne
    # primary keys are automatically formed by django
    # how django handles profiles: https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
    user = models.ForeignKey(User)

    def __unicode__(self):
        return self.User

class UserPlayList(models.Model):
    # don't capitalise attributes, if you haven't seen PEP8 before, do now: http://www.python.org/dev/peps/pep-0008/
    profile = models.ForeignKey(User)
    playlist = models.ForeignKey(PlayList)

class Video(models.Model):
    video_url = models.URLField(max_length=200, null=True, blank=True, help_text="Link to video")

    def __unicode__(self):
        return self.video_url

class VideoPlayList(models.Model):
    video = models.ForeignKey(Video)
    play_list = models.ForeignKey(UserPlayList)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2013-02-14
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多