【发布时间】:2021-10-23 16:02:18
【问题描述】:
因此,如果我有一个简单的模型作为我的 PK 的来源,如下所示:
class PostCreation(models.Model):
pk = models.AutoField(primary_key=True)
post = models.OneToOneField(Post, on_delete=models.CASCADE)
我想做的是在创建博文之前创建博文的 PK。 我的理由是我希望我上传的图像/文件格式为
/media/blogPK/files
所以我的 Post 会从上面的 PostCreation 类中设置一个 id/PK 字段 伪代码如下:
id = PostCreation()
FileField(upload_to='{}{}{}'.format(id, '/', files))
但是如何先创建 PK,然后将其传递给我的 Post 模型 然后将 Post is/pk 设置为 PostCreation 的那个?
我将使用 ModelForm 输出帖子内容、描述/日期等字段,因此当我访问该视图时,我希望即使用户确实提交了 pk/id Post 模型的内容。
我该怎么做?有可能吗?
谢谢
【问题讨论】:
-
你为什么不直接在你的 Post 模型中存储那个 PK 字段呢?
-
来自 Django 文档:
There’s no way to tell what the value of a [primary key] will be before you call save(), because that value is calculated by your database, not by Django.在模型上调用 save() 之前设置 FileField 是否重要?或者,有ways to get the database to reserve a primary key value,但它有点凌乱且不便携。 -
@EnePaul 因为我想使用 PK 将文件发布到以 PK 为名称的文件夹中。但我不能,除非在我点击提交之前已经创建了 PK。
标签: django django-models django-forms