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

前端 未结 4 1458
一生所求
一生所求 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:07

    Context

    Had the same issue. Solved it attributing an id to the current object by saving the object first.

    Method

    1. create a custom upload_to function
    2. detect if object has pk
    3. if not, save instance first, retrieve the pk and assign it to the object
    4. generate your path with that

    Sample working code :

    class Image(models.Model):
        def upload_path(self, filename):
            if not self.pk:
                i = Image.objects.create()
                self.id = self.pk = i.id
            return "my/path/%s" % str(self.id)
        file = models.ImageField(upload_to=upload_path)
    

提交回复
热议问题