Recently, I wanted to port a database application I had written using ASP into Rails. I had only made it so far using Ruby, but I still had the SQLite database sitting around. So, I started working on defining the models in Django and it prompted some questions:
What was the best way to start defining your model? Do you write it in django first and then rely on syncdb to build the database? What if you have an existing model? After some looking around, I found the command django-admin.py inspectdb. Which allowed me to automatically create the models.py file based on structure I had already defined in the SQLite database with the commands:
export DJANGO_SETTINGS_MODULE=mysite.settings
cd mysite
python manage.py inspectdb > models.py
However this introduced some issues all its own. In particular, fellow developer Milan Andric pointed out that I needed to:
- remove all instances of id = models.IntegerField(primary_key=True)
django automatically gives every model a primary key. - I also needed to remove:
class Meta:
db_table = u'...'
To view the difference in the code once it was cleaned up, see this diff
Additionally, Milan noted that I likely benefit from using __unicode__() to name my objects.
This morning, in looking over some previous conversations, I remembered that Milan had also suggested I look into the django-command-extensions module which provides some nice command line tools that (among other things) allows you to easily generate image files of you schema from django models. You can see an image of the current data model here:
Which I created this using the command:
python manage.py graph_models yourproject | dot -Tpng -o yourfilename.png
You can download the django-command-extensions here:
http://code.google.com/p/django-command-extensions/
You can also watch a video of the the django-command-extensions tools in action here http://www.vimeo.com/1720508 .