Saturday, 25 January 2014

Let's do ... django!

pgmodeler is a sweet tool for creating database in postgresql from scratch. However it doesn't export to django model file, so what do you do?

First, export the database to your postgresql database

Then in your django project modify your settings.py with the database name, credentials, host, port, etc...and run the following command:


python manage.py inspectdb > APP_NAME/model.py

and voila! Here is an example:


from __future__ import unicode_literals
from django.db import models

class Family(models.Model):
#    familyid = models.BigIntegerField(db_column='familyId', primary_key=True)  
    familyid = models.AutoField(db_column='familyId', primary_key=True)     #Change BigIntegerField to AutoField -> Auto increment field!
    familyname = models.CharField(db_column='familyName', max_length=255)
    familydescription = models.CharField(db_column='familyDescription', max_length=1000)
    publicviewsettingid = models.SmallIntegerField(db_column='publicViewSettingId', blank=True, null=True) 
    createon = models.DateTimeField(db_column='createOn', blank=True, null=True) 
    class Meta:
        managed = False         ####<-------------- NOTE THAT FOR "manage.py syncdb"  to work, you need to REMOVE THIS LINE
        db_table = 'Family'


After modifying the model.py to your need and remove the "managed=False" line for the tables that you want to create, you can now drop the table and recreate with "manage.py syncdb"

Now that you already have the models in place, having some dummy data would be nice  so let's use autofixture for that!
Install autofixture:

pip install django-autofixture

Add "autofixture" into the list of INSTALLED_APPS in "settings.py",
run this command to generate 5 Family dummy data:

python manage.py loadtestdata PROJECT.Family:5

And now, for future usage we can put it into "fixture" folder under family application, let's call it initial_data.json:

python manage.py dumpdata > family/fixtures/initial_data.json




1 comment:

  1. So you have had good luck using pgmodeler with django? The fact that pgmodeler will not import updates to the django models is a major issue.

    ReplyDelete