A few days ago I mentioned Changeset 384 which included a new command, django-admin.py inspectdb <dbname>. It has also been tweaked and improved since it was initially committed. The other day I tried it out on a simple database structure, but I decided to throw a more complex example at it.
I decided to take the final depot application from the excellent Agile Web Development with Rails book. Beta books rule by the way. I executed the SQL in
rails-code/depot_final/db/create.sql from the the code tarball to set up the database structure. I then created a new project with
django-admin startproject and edited
settings/main.py to tell Django how to log in to my mysql database. After exporting the correct
DJANGO_SETTINGS_MODULE I ran
django-admin.py inspectdb depot_rails which gave me the following model:
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Add primary_key=True to one field in each model. # Feel free to rename the models, but don't rename # db_table values or field names. # # Also note: You'll have to insert the output of # 'django-admin.py sqlinitialdata [appname]' # into your database. from django.core import meta class LineItem(meta.Model): db_table = 'line_items' fields = ( meta.IntegerField('id'), meta.IntegerField('product_id'), meta.IntegerField('order_id'), meta.IntegerField('quantity'), meta.FloatField('unit_price'), ) class Order(meta.Model): db_table = 'orders' fields = ( meta.IntegerField('id'), meta.CharField('name', maxlength=100), meta.CharField('email', maxlength=255), meta.TextField('address'), meta.CharField('pay_type', maxlength=10), meta.DateTimeField('shipped_at'), ) class Product(meta.Model): db_table = 'products' fields = ( meta.IntegerField('id'), meta.CharField('title', maxlength=100), meta.TextField('description'), meta.CharField('image_url', maxlength=200), meta.FloatField('price'), meta.DateTimeField('date_available'), ) class User(meta.Model): db_table = 'users' fields = ( meta.IntegerField('id'), meta.CharField('name', maxlength=100), meta.CharField('hashed_password', maxlength=40), )
Per the comment block at the top, you’re not home free yet, but at lot of tedious work has been done for you. This should definitely jumpstart the porting of existing applications to the Django platform.