import os from django.db import connection, models def prefetch_id(instance): """ Fetch the next value in a django id autofield postgresql sequence """ cursor = connection.cursor() cursor.execute( "SELECT nextval('{0}_{1}_id_seq'::regclass)".format( instance._meta.app_label.lower(), instance._meta.object_name.lower(), ) ) row = cursor.fetchone() cursor.close() return int(row[0]) def make_file_path(instance, filename): return os.path.join(instance._meta.app_label, instance._meta.object_name, instance.id,filename) class SomeModel(models.Model): some_file = FileField(upload_to=make_file_path) def save(self, *args, **kwargs): if not self.id and some_file: self.id = prefetch_id(instance) super(SomeModel, self).save(*args, **kwargs)