Using Django Models

At work, we are currently busy building a report automation tool, using Django 1.6.4 for the frontend part of the application and some Python for the backend.

Basically, we define what a report looks like on the Django frontend, and then run some Python scripts on the backend to create the report we defined.

The beautiful thing about Django is how it interfaces with a database. You define your data models in and Django then creates those models as database tables for you in whatever database instance you’ve got it pointed at.

Let’s create a simple data model, something that closely resembles what I’m currently working on:

from django.db import models

class ReportingModule(models.Model):
    name = models.CharField(max_length=30)
    description = models.CharField(max_length=250, blank=True)

class Report(models.Model):
    name = models.CharField(max_length=30)
    description = models.CharField(max_length=250, blank=True)
    reporting_modules = models.ManyToManyField(ReportingModule, blank=True)

So we can define different reporting modules and then link those models to individual reports. Once you run Django’s syncdb command, it will create those tables for you, even creating a special table to handle the many-to-many relationship between Report objects and Reporting Module objects.

How do you use these models to insert data into your database?

from your_project.models import Report, ReportingModule

# takes your report object that you created... 
# and saves it in the database. Crazy, right?
report = Report(name='Test Report', description='This is a test report')

But what about that many-to-many field, you ask?

# note that we don't need a description field
reporting_module1 = ReportingModule(name='Test Module 1')

reporting_module2 = ReportingModule(name='Test Module 2')

reporting_module3 = ReportingModule(name='Test Module 3')

Okay, but how do we ‘link’ our modules to our report? Let’s say our report contains modules 1 and 3:


All of this is kinda awesome, right? Not to mention pretty.

Django is the first web framework that I’ve worked with that allows me to create database tables from inside the framework. When I started this project, I took a day or two to design the database and then tried to figure out how Django is supposed to interface with my database models that I’ve designed. Which was the wrong way of going about things. Once I found out about the syncdb command, it didn’t take me long to figure out that I’m using Django wrong and I should let Django handle the database interactions for me. I don’t even log into a database client at all now.

Look, I know there are other frameworks that work exactly like this with regards to database models. I just haven’t used one as extensively as I’ve used Django. It might be old news to a lot of you out there, but it’s pretty amazing to me.