【问题标题】:Using a model as a source for a PK for diffrent model?使用模型作为不同模型的 PK 源?
【发布时间】: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


【解决方案1】:

您所要做的就是使用基于最新保存的对象id 的初始值填写表单。然后:

views.py : 实例化表单的地方

def create_post(request):

    # Some logics here ...

    # Retrieve the last object id from the db
    latest_index = Post.objects.last().id
    # Format the folder name based on the index
    upload_to = f"{latest_index + 1}/files"
    # Set the initial value of the folder path
    form = PersonForm(initial={'file_field_name': upload_to})

    # Some logics here ...

注意:注意file_field_name是模型中FileField的名称

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2018-02-02
    • 1970-01-01
    • 2019-03-26
    相关资源
    最近更新 更多