Using Postgres 'serial' in Django (other than primary key)
I have created a custom field for my model BigSerialField
as shown below.
class BigSerialField(models.Field):
description = 'Big Serial of Postgres'
def __init__(self, *args, **kwargs):
super(BigSerialField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(BigSerialField, self).deconstruct()
return name, path, args, kwargs
def db_type(self, connection):
return 'bigserial'
def from_db_value(self, value, expression, connection, context):
if value is None:
raise Exception('Big Serial cannot be null!')
return int(value)
def get_prep_value(self, value):
return None
def get_db_prep_value(self, value, connection, prepared=False):
return None
def get_db_prep_save(self, value, connection):
return self.get_db_prep_value(value, connection)
def to_python(self, value):
if isinstance(value, int):
return value
if value is None:
raise Exception('Big Serial cannot be null!')
return int(value)
This raises an error because the ORM is now trying to pass null
to the field on save. A keyword is required instead of Postgres DEFAULT
. However, when I try to send 'default'
instead None
to get_db_prep_save
, Postgres throws an error because it interprets it correctly 'default'
as a string.
So how does Django send the keyword DEFAULT
to Postgres?
source to share
No one has answered this question yet
Check out similar questions: