在 Django 中使用 Postgres 'serial'(主键除外)

vir*_*mic 5 python django postgresql

我为我的模型创建了一个自定义字段,BigSerialField如下所示。

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)
Run Code Online (Sandbox Code Playgroud)

这会引发错误,因为现在 ORM 尝试null在保存时传递到该字段。Postgres 需要DEFAULT关键字。但是,当我尝试发送 in'default'而不是Noneinget_db_prep_save时,Postgres 会引发错误,因为它'default'正确地解释为字符串。

那么,Django 中如何将DEFAULT关键字发送到 Postgres 呢?