Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a Django model field with a PostgreSQL function as default value

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?

like image 882
David Avatar asked Nov 11 '11 15:11

David


2 Answers

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

like image 179
Danny W. Adair Avatar answered Oct 13 '22 01:10

Danny W. Adair


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

like image 22
Chris Pratt Avatar answered Oct 12 '22 23:10

Chris Pratt