21 February

How to add a new field to an existing model

The problem with adding new fields is two-fold:

  1. Your sample data do not contain values for the new field. This can be addressed by making sure that it is optional. Here is the example we saw in class:

        pages = models.IntegerField(blank=True, null=True)
  2. The syncdb command will only create new tables, it does not modify existing tables in the database. This can be addressed in development by removing the dbfile and building it again:

    liucs:~/cs164/bookswap$ rm -f dbfile
    liucs:~/cs164/bookswap$ python manage.py syncdb --noinput
    liucs:~/cs164/bookswap$ python manage.py loaddata sample
    

    The --noinput option means that it will not ask for (and will not create) a super-user. This is okay, because we’re adding user data in the loaddata step anyway.

    There are ways to modify the tables in the DB without deleting everything, but usually I wouldn’t bother in development. Once we reach production, of course, we would need a sound and convenient way to adjust the models with little or no downtime.

comments powered by Disqus

 

©2012 Christopher League · some rights reserved · CC by-sa