Reputation: 1030
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?
Upvotes: 6
Views: 2760
Reputation: 12968
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
Upvotes: 4
Reputation: 239400
You have to do it in SQL yourself. Django doesn't support that. It's a feature of it's database independence.
Upvotes: 1