我正在建立一个博客,该博客收集了我最喜欢的视频,很有趣。下面是我的应用程序中的模型:
# 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()
我是否正确连接了这些?
答案 0 :(得分:0)
我认为关系应该是这样的:
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>]>