Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default column value in the db using django 1.7.3/postgres migrations?

It seems like default value on columns is only on the ORM layer, and is not actually setting a default value in the DB. At the same time, the ID key for example has a default modifier in the database, which tells me it is possible to do that, but not sure how?

Example code:

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

creates the following table:

  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

Is there a way to have the migration set default current_timestamp in the created_at modifiers? If not, is there a way to pass in raw SQL migrations? I need it because the database is used by other processes (e.g. batch processes) which I don't want to have to enforce things like default values on the application layer.

like image 933
Isaac Avatar asked Jan 24 '15 20:01

Isaac


1 Answers

I would put your code in a RunSQL operation, something like:

class Migration(migrations.Migration):

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

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

I think this approach is cleaner than trying to override apply(). The API makes it easy to add the SQL for the reverse operation, and because the migration infrastructure understands the semantics of RunSQL it might be able to make better decisions. (For example, it knows not to squash migrations across a migration that has a RunSQL operation.)

like image 188
Kevin Christopher Henry Avatar answered Sep 19 '22 11:09

Kevin Christopher Henry