Prefetch id for Postgresql backend

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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)

More like this

  1. Image uploader to use with file uploader from http://github.com/valums/file-uploader by tgdn 2 years, 3 months ago
  2. Improved Pickled Object Field by taavi223 4 years, 8 months ago
  3. Function/Stored Procedure Manager by axiak 6 years, 10 months ago
  4. Admin page without inlines dinamically by davmuz 1 year, 10 months ago
  5. load m2m fields objects by dirol 3 years, 10 months ago

Comments

(Forgotten your password?)