使用一个模型作为不同模型的PK的源?



如果我有一个简单的模型,我想作为我的PK的来源,像这样:

class PostCreation(models.Model):
pk = models.AutoField(primary_key=True)
post = models.OneToOneField(Post, on_delete=models.CASCADE)

我想做的是在博客文章被创建之前创建它的一个PK。我的理由是我希望我上传的图像/文件的格式为

/media/blogPK/files

所以我的帖子将有一个id/PK字段设置从上面的PostCreation类伪代码如下:

id = PostCreation()
FileField(upload_to='{}{}{}'.format(id, '/', files))

但是我如何首先创建PK,然后将其传递给我的Post模型呢然后将Post is/pk设置为PostCreation?

我将使用ModelForm输出Post内容、Description/Date等字段,所以当我要访问那个视图时,我希望pk/id已经生成,即使用户确实提交了Post模型的内容

我该怎么做?这可能吗?

Thx

您所要做的就是用基于最近保存的对象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的名称