Django: Access primary key in models.filefield(upload_to) location

前端 未结 4 1452
一生所求
一生所求 2020-12-16 16:51

I\'d like to save my files using the primary key of the entry.

Here is my code:

def get_nzb_filename(instance, filename):
    if not instance.pk:
            


        
4条回答
  •  暖寄归人
    2020-12-16 17:20

    It seems you'll need to pre-generate your File models with empty file fields first. Then pick up one and save it with the given file object.

    You can have a custom manager method like this;

    def create_with_pk(self):
        instance = self.create()
        instance.save()     # probably this line is unneeded
        return instance
    

    But this will be troublesome if either of your fields is required. Because you are initially creating a null object, you can't enforce required fields on the model level.

    EDIT

    create_with_pk is supposed to be a custom manager method, in your code it is just a regular method. Hence self is meaningless. It is all properly documented with examples.

提交回复
热议问题