Once the project is created, we can focus on its features. Now, we can define our first User Story. In the purpose of our project, we’ll want to follow RSS feeds. We’ll need to inform our software about those feeds. Usually, the first User Story is “I want to see a form to submit my data“. Usually, to complete this User Story, developers focus on the form. That is not the approach with Django. The data is most important than the form, so we’ll start with the data, Django will make the rest much easier.
Django also makes the data manipulation easy with the Model Layer. This is the abstraction layer where you are going to define and manipulate your data model. So first we have to define and tell Django what our data is.
At this step, we plan to build an app which will load, parse and display RSS feeds. So, the system will need to know where to find the feeds, and then to parse all the items. The user should just have to provide the URL of the feed. This will be our first model and form. A very simple model which will let us see how Django deals with it.
Creating our first model
We will create a model (a class definition) for the URL of one feed. This model will have three fields: the URL of course, a human readable name and the last updated date. Edit the models.py file in the reader package as follow :
from django.db import models class SourceUrl(models.Model): name = models.CharField(max_length = 100) url = models.URLField(max_length = 200); lastVisited = models.DateTimeField(auto_now = True)
For the best understanding of the models, there are two important pages in the documentation: the one explaining the models, and the one explaining the fields. What you must remember is that each model is a class that subclasses django.db.models.Model. Thus, each attribute represents a database field.
So, a model is just a class with attributes ? No, Models are real classes and you can use methods. It is a good practice to redefine the __unicode__ method of your classes. Lets do it.
from django.db import models class SourceUrl(models.Model): name = models.CharField(max_length = 100) url = models.URLField(max_length = 200); lastVisited = models.DateTimeField(auto_now = True) def __unicode__(self): return self.name
The attributes are the most important elements of a model. A model defines a table in the database and its attributes defines the fields. You can see that all the attributes defined here are represented by instances of Field classes, and each type of field tells Django what type of data the field holds.
We also gave some arguments to each field. Some are required, others are optional. For instance, the max_length is required as it will be used for the database schema and for data validation. Once again, to get the entire list of fields available and their arguments, you can check the documentation’s reference. As homework, you can modify this model to fit other constraints you may see.
Creating the database table
With this model declared and the application activated, Django is available to create a database-access API to access the objects in the database. But at this point, there is no sourceurl table in the database. Django can create it automatically for you. You remember the last command we run in the previous post ? You can execute it once again.
python manage.py syncdb
The output will indicate that the table reader_sourceurl has been created. What is the SQL executed ? Just run the command
python manage.py sql reader
And the output should be something similar to
BEGIN; CREATE TABLE "reader_sourceurl" ( "id" integer NOT NULL PRIMARY KEY, "name" varchar(100) NOT NULL, "url" varchar(200) NOT NULL, "lastVisited" datetime NOT NULL ) ;
Of course, this output is specific to the database you have declared. As you can see, in the process of creating the tables, Django follows some conventions. In our case, it named the table by concatenating the application name to the model name and added a primary key. Of course, all of those conventions can be overridden. Should you or not ?
For a simple application like this one, you really don’t have to care about it, just keep the convention names and let Django define your database model. Just focus on the applicative code. Remember that Django may create the tables for you, but you are free to design your database by yourself, and that is certainly what you would do in larger projects. Just keep in mind that if the database was designed outside Django, you just have to inform Django of the connection.
What Django does for you, and what you should do by yourself
As we are in the database creation subject, you may wonder what was the action of the syncdb we executed in the previous post. Syncdb creates all the tables for all apps defined in INSTALLED_APPS. So, the previous execution created the tables for the default applications. For every app in INSTALLED_APPS, you can execute
python manage.py sql appname
where appname is the name of an application. You will then see the SQL Django executed.
Remember that syncdb will only create missing tables. So you will have to execute it each time you add an application or a model. Syncdb will not alter a table, if you need to update a database schema, you’ll have to do it yourself. Well, during the development process, you’ll most certainly drop the database and recreate it, but remember to provide a SQL update script when you’ll go in production.
So, we have written our first model, what will happen if we launch our server ? Try it, and no, nothing changed as we haven’t declared any view. Besides, we have created a model, but we still don’t have the form to enter the data. With the help of Django, we are just one step away from fulfilling the UserStory.
As usual, if you have any question, feel free to ask them in the comments.