【发布时间】:2019-07-11 05:48:44
【问题描述】:
我有一个 Post 模型、一个 Image 模型和一个 Channel 模型。我在连接到 Post 模型的 Image 模型中有一个外键。此外,我正在尝试添加一个连接到 Channel 模型的可为空的外键。
class Image(models.Model):
post = models.ForeignKey(Post, null=True, blank=True, on_delete=models.CASCADE)
comment = models.ForeignKey(Comment, null=True, blank=True, on_delete=models.CASCADE)
news = models.ForeignKey(News, null=True, blank=True, on_delete=models.CASCADE)
message = models.ForeignKey(Message, null=True, blank=True, on_delete=models.CASCADE)
channel = models.ForeignKey(Channel, null=True, blank=True, on_delete=models.CASCADE)
file = ProcessedImageField(upload_to='uploads/%Y/%m/%d/',
processors=[Transpose()],
format='JPEG',
options={'quality': 50},
blank=True)
我担心通道字段将大部分为空,因为我每个通道只需要一张图像。但是图像必须与帖子相关联。因此,每个频道都有一个与帖子相关联的图像。但是,帖子和图片的数量会比一个频道多得多,所以 Image 模型中的频道字段大部分时间都会被浪费掉。
我想到的另一个解决方案是专门为 Channel 模型创建一个新的图像模型,当创建新的图像实例时,手动从原始的 image-post 连接实例中复制图像。
class ChannelImage(models.Model):
channel = models.OneToOneField(Channel)
post = models.OneToOneField(Post)
file = ProcessedImageField(upload_to='uploads/%Y/%m/%d/',
processors=[Transpose()],
format='JPEG',
options={'quality': 50},
blank=True)
//copy a file from the original post
所以我的问题是,在模型中有这么多浪费的空外键的成本是多少?模型中有很多浪费的外键可以吗?
【问题讨论】:
标签: django django-models