0

So if I have a simple model that I want as a source of my PK like so:

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

What I want to do is create a PK of a blog post before the post has been created. My reasoning is I want the images/files I upload to be in a format of

/media/blogPK/files

So my Post will have a id/PK field set from the PostCreation class above And the Pseudo code is below:

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

But how can I create the PK first and then pass it to my Post model and then set the Post is/pk to that of PostCreation?

I's going to be using ModelForm to output the fields for the Post content, Description/Date etc so when I goto visit that view I want the pk/id already made even if the user does submit the content of the Post model.

How can I do this? Is it possible?

Thx

Definity
  • 691
  • 2
  • 11
  • 31
  • Why don't you store that PK field directly in you Post model? – lucutzu33 Oct 23 '21 at 16:06
  • 1
    From the Django docs: `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.` Is it important that the FileField be set before save() is called on your model? Alternatively, there are [ways to get the database to reserve a primary key value](https://stackoverflow.com/questions/18411384/reserving-mysql-auto-incremented-ids), but it's kind of messy and nonportable. – Nick ODell Oct 23 '21 at 16:09
  • @EnePaul becuases I wanted to use the PK to post the files to a folder that has the PK as its name. But I cant unless the PK has been created before I click submit. – Definity Oct 23 '21 at 16:39

1 Answers1

0

All you have to do is to fill the form with an initial value based on the latest saved object id. Then :

views.py : where you instantiate the form

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 ...

NB : Note that file_field_name is the name of the FileField in the model

Rvector
  • 2,312
  • 1
  • 8
  • 17