Skip to content

Instantly share code, notes, and snippets.

@Guest007
Created July 16, 2018 14:10
Show Gist options
  • Select an option

  • Save Guest007/bed81d6331fb87208665de8bd4326bb0 to your computer and use it in GitHub Desktop.

Select an option

Save Guest007/bed81d6331fb87208665de8bd4326bb0 to your computer and use it in GitHub Desktop.
Prefetch id for Postgresql backend
# from https://djangosnippets.org/snippets/2731/
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment