Migrating Your App to Django

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.

27 Responses to “Migrating Your App to Django”


  1. 1 Robin Munn Aug 6th, 2005 at 5:51 am

    It’s worth noting that the model-creation syntax will be changing sometime before Django’s official 1.0 release, in a backwards-incompatible way. Instead of specifying fields with:

    fields = (
    meta.CharField('name', maxlength=50),
    meta.IntegerField('age')
    )

    You’ll specify fields with the following syntax:

    name = meta.CharField(maxlength=50)
    age = meta.IntegerField()

    Watch Django ticket #122 to see when the above change is actually applied to the Django repository.

  2. 2 Oklahoma Jul 8th, 2008 at 12:35 am

    good luck,

  3. 3 Рекламное агентство Jun 24th, 2009 at 10:26 pm

    дето тоже читал

  4. 4 OranymnHauddy Jul 5th, 2009 at 7:04 am

    I think, that you are not right. I am assured.

  5. 5 uticupTHigcog Jul 21st, 2009 at 9:56 am

    ob es die Analoga Gibt?

  6. 6 sport-markt Aug 7th, 2009 at 3:43 pm

    Registriert

  7. 7 annoripaw Aug 23rd, 2009 at 2:28 pm

    It still that?

  8. 8 LarryXA Nov 6th, 2009 at 9:44 pm

    Thx, this has definitely made my day!

    _______________________
    wtf

  9. 9 vpowerauto Nov 7th, 2009 at 1:58 am

    Как Вы сами сказали “ну я не говорю о блогах”, но тогда можно “не говорить” о многих разработках.

  10. 10 spourpotmet Nov 21st, 2009 at 9:48 pm

    Прочитай все SMS и просмотри звонки своих друзей или второй половинки. Уникальная технология перехвата. СДЕЛАТЬ ЗАПРОС

  11. 11 swaxiaTah Dec 7th, 2009 at 7:15 pm

    thanks repayment for the great low-down…

  12. 12 Ornalkutinura Jan 29th, 2010 at 10:26 pm

    Мдаа..интересный пост. Вот только об этом пишут все кому не лень. Ини что, читают друг у друга новости и своим языком их пересказывают? В сео блогах это особенно заметно. Народ, столько новостей интересных в мире…

  13. 13 Ornalkutinura Feb 3rd, 2010 at 1:16 am

    мало инфы. Вы бы хоть постарались написать посто-то. Всё-таки вас читает много народа, да и в поисковике по этой теме вы на первой странице…ай яй яй…не хорошо :(

  14. 14 nowsDariwonee Feb 16th, 2010 at 10:38 pm

    А мне всё понравилось. Забрал в букмарки.

  15. 15 nowsDariwonee Feb 17th, 2010 at 9:15 am

    Хороший блог, удачи в нашем нелёгком деле :)

  16. 16 nowsDariwonee Feb 17th, 2010 at 10:40 pm

    Мне ваш сайт понравился. Так же всех с днём защитника отечества :)

  17. 17 nowsDariwonee Feb 18th, 2010 at 11:16 pm

    Можно было бы и поподробнее написать

  18. 18 nowsDariwonee Feb 19th, 2010 at 10:05 pm

    Прям шедевр, а не пост. Очень искал инфу на эту тему.

  19. 19 nowsDariwonee Feb 26th, 2010 at 7:43 pm

    Горячее однако обсуждение :) Я бы к посту ещё фоток добавил бы…

  20. 20 nowsDariwonee Feb 28th, 2010 at 9:23 pm

    Хороший сайт, удачи :)

  21. 21 Ornalkutinura Mar 6th, 2010 at 9:50 pm

    Вот огромное человческое спасибо вам за этот блог. Кроме этого поста нашёл ещё кучу интересного для себя. Теперь буду заходить сюда постоянно..Я Ваш читатель :)

  22. 22 Ornalkutinura Mar 7th, 2010 at 11:18 am

    Хотела бы обменяться с вами ссылочкой. У меня блог схожей тематики. Если интересно, то напишите на xizabella24@gmail.com

  23. 23 Ornalkutinura Mar 10th, 2010 at 12:09 am

    Понравился Ваш сайт! В рунете вообще мало чего дельного в блогах пишут. Всё стараются друг у друга скопировать посты. Года 2 назад было интересно ходить по разным блогам-видно было сразу-люди старались писать посты..а щас уже только для яндекса и стараются. Вообщем желаю продолжать Вам в Том же духе.
    С уважением Ваш читатель.

  24. 24 Ornalkutinura Mar 11th, 2010 at 1:41 pm

    +1 к предыдущему коментарию..

  25. 25 Ornalkutinura Mar 14th, 2010 at 3:08 pm

    ООО..давно искал. Забрал в букмарки. Автор, пишите почаще..не забрасывайте блог…Кстати не мешало бы диз поменять.

  1. 1 Enquanto isso, na repartio… » Blog Archive » Comparaes entre Web Frameworks Pingback on Aug 17th, 2005 at 1:49 pm
  2. 2 a32ea9cb24c9 Trackback on May 9th, 2008 at 4:09 pm

Leave a Reply