3

Supose there is a site with 1 million users, and they all have at least one profile image (maybe more).

I'm not sure, but I think that storing all that images in one folder is not very smart (in terms of speed, because there need some time to find one image between a million and more images in that folder need more time to find anything there).

So, as a variant we can store that images in different folders (even if few levels of nested folders).

For example: users with id 1-1000 will store their images in folder 1; users with id 1001-2000 will store their images in folder 2 and so on...

To do this we need upload_to parameter of ImageField must be dynamic (dependent on user id or in other words self.id).

Are there any ways to make it dynamic? Or maybe there are some more proper ways of implementing this scenario?

Thanks in advance!!!

Vitalii Ponomar
  • 10,686
  • 20
  • 60
  • 88

1 Answers1

1

You can define a function as the upload_to parameter... in your case:

def upload_to_by_id(instance, filename):
    if instance.id:
        # you already have an id (updating a model with a new file)
        folder = str(self.id/1000 +1)
    else:
        # maybe you still don't have an id!! this can happen a lot... :/
        folder = 'tmp'

    return '%s/%s' % (folder, filename)

Hope this helps!

Julian
  • 702
  • 4
  • 14