繁体   English   中英

模型关系 - ForeignKey还是OneToMany?

[英]Model relationship - ForeignKey or OneToMany?

我正在制作一个博客,收集我最喜欢的视频,以获得乐趣。 以下是我的应用程序中的模型:

# I want to categorize the videos
class blog(models.Model):
    name = models.CharField(max_length=255) #name can be dogs, cats, cars
    relatedVideo = models.ForeignKey(video, on_delete=models.CASCADE)

class video(models.Model):
    name = models.CharField(max_length=255) #the video name 
    description = models.TextField()

我是否正确连接了这些?

我认为关系应该是这样的:

class blog(models.Model):
    name = models.CharField(max_length=255) #name can be dogs, cats, cars

class video(models.Model):
    name = models.CharField(max_length=255) #the video name 
    description = models.TextField()
    blog = models.ForeignKey(blog, on_delete=models.CASCADE, related_name="related_videos")

    def __str__(self):
        return self.name

通过这种ForeignKey关系意味着,一个博客可以拥有多个视频。 你可以像这样使用这种关系:

>>b = blog.objects.create(name="Some Name")
>>v1 = video.objects.create(blog=b, name="Video 1")
>>v2 = video.objects.create(blog=b, name="Video 2")
>>b.related_videos.all()
<QuerySet [<video: Video 1>, <video: Video 2>]>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM