6

Is it possible to write a Django model with a field that uses a PostgreSQL function as its default value? Here's a simple example using txid_current() as a default value:

% psql
mydb=# CREATE TABLE test (
    label text default '', 
    txid BIGINT DEFAULT txid_current()
);
CREATE TABLE
mydb=# \d test
           Table "public.test"
 Column |  Type  |       Modifiers        
--------+--------+------------------------
 label  | text   | default ''::text
 txid   | bigint | default txid_current()

mydb=# INSERT INTO test (label) VALUES ('mylabel');
INSERT 0 1
mydb=# select * from test;
  label  |  txid  
---------+--------
 mylabel | 192050
(1 row)

A Django model for that table might look like

class Test(models.Model):
    label = TextField('Label', default='')
    txid = BigIntegerField('txid', default=???)

Is there a way to specify the database function as a default value or do I need to add the default in PostgreSQL as a separate step after running syncdb?

2 Answers 2

4

You can specify a callable as "default" https://docs.djangoproject.com/en/dev/ref/models/fields/#default

and let your callable execute raw SQL to get the value you're after https://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly

Regarding your txid_current(), make sure to read https://docs.djangoproject.com/en/dev/topics/db/transactions/#django-s-default-transaction-behavior

Sign up to request clarification or add additional context in comments.

1 Comment

How do I get the database that I should use to execute the function?
1

You have to do it in SQL yourself. Django doesn't support that. It's a feature of it's database independence.

1 Comment

Thanks. I've only ever used PostgreSQL with Django but knew that MySQL & sqlite both have functions. I see now that MySQL doesn't allow functions as default values so my example really would be PostgreSQL specific. Being able to pass some additional details to insert into the CREATE TABLE statement, depending on what your back end understands, seemed plausible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.