如何使用django 1.7.3 / postgres迁移在db中设置默认列值?

时间:2015-01-24 20:37:24

标签: python django postgresql django-models django-migrations

列上的默认值似乎仅在ORM层上,并且实际上并未在DB中设置默认值。同时,ID键例如在数据库中有一个默认修饰符,它告诉我可以这样做但不确定如何?

示例代码:

class Host(models.Model):
    name = models.CharField(max_length=255, null=False)
    created_at = models.DateTimeField(default=datetime.now, blank=True)

创建下表:

  Column   |           Type           |                          Modifiers                          
------------+--------------------------+-------------------------------------------------------------
 id         | integer                  | not null default nextval('myapp_host_id_seq'::regclass)
 name       | character varying(255)   | not null
 created_at | timestamp with time zone | not null

有没有办法在default current_timestamp修饰符中设置迁移集created_at?如果没有,是否有办法传递原始SQL迁移?我需要它,因为数据库被其他进程(例如批处理进程)使用,我不想在应用程序层上执行默认值等操作。

2 个答案:

答案 0 :(得分:8)

我会将您的代码放在RunSQL operation中,例如:

class Migration(migrations.Migration):

dependencies = [
    ('myapp', 'previous_migration'),
]

operations = [
    migrations.RunSQL("alter table myapp_host alter column created_at set default current_timestamp"),
]

我认为这种方法比试图覆盖apply()更清晰。 API使得为反向操作添加SQL变得容易,并且因为迁移基础结构理解RunSQL的语义,所以它可能能够做出更好的决策。 (例如,它知道不会在具有RunSQL操作的迁移中压缩迁移。)

答案 1 :(得分:0)

这对我有用。我仍然想知道是否有更清洁的解决方案:

class Migration(migrations.Migration):

dependencies = [
    ('myapp', 'previous_migration'),
]

operations = []

def apply(self, project_state, schema_editor, collect_sql=False):
    cursor = connection.cursor()
    cursor.execute("alter table myapp_host alter column created_at set default current_timestamp")
    return super(Migration, self).apply(project_state, schema_editor, collect_sql)