elynch
elynch

Reputation: 2240

Django model with a custom field that uses a database default

I am trying to implement a subclass of IntegerField to use a default method on my Postgres database, rather than a django default method (I know this is a hot topic). In order to do so I've modified the following method on my custom field

    def get_db_prep_save(self, value, connection):
        return 'default'

However, when django executes the SQL statement it looks something like this:

INSERT INTO my_table ('default_column') VALUES ('default')

The insertion fails because the default keyword is surrounded by quotes. The following SQL statement works:

INSERT INTO my_table ('default_column') VALUES (default)

I've noticed that the problem is in the way django performs cursor.execute by passing the SQL statement and parameters separately, thus causing the default keyword to be surrounded by quotes.

I am trying to find a way to resolve this without re-writing the postgres backend

Help is much appreciated

Upvotes: 4

Views: 253

Answers (1)

jazz
jazz

Reputation: 2379

Reference

from psycopg2.extensions import AsIs 

def get_db_prep_save(self, value, connection):
    return AsIs('default')

should do it.

Upvotes: 1

Related Questions