Building a simple Django Web Application: Part 1

Every passionate python user knows that the power of Python lies within it being object oriented. Django is designed to leverage the object oriented power in Python. Django manages data and the operations performed on it through objects referred to as models. 

A model to Django is what a schema is to SQL, it defines the structure, field types, constraints as well as many other things. However, it is extremely significant that you understand that both the database and the model are independent of each other. Django allows you to choose the database engine you favor by specifying it in settings.py, but it also handles the task of implementing the model you've structured, and it's communication, onto the database you've selected, ultimately making work much easier for you. 

Before you start writing code, give some thought about your project. What constitutes an object? Furthermore, what are the relationships between your different objects? (One-to-One, One-to-Many, and Many-to-Many.) And finally, what data needs to be stored ?

By building each object individually as a model, this makes your code readable, expandable, and maintainable. It's worthy to draw a UML diagram, specifying the different models and their relationships.

Writing the Model 

Models are defined in the file models.py, found in the app folder. Don't worry about it's location now, it will be much more clear when we begin the exercise. For the time being take a look below at a typical model and how it's written. 


from django.db import models

class ModelName(models.Model):

    fieldName = models.CharField(max_length=100)
    
    fieldEmail = models.EmailField(primary_key=True)

    
    def __str__(self):
        
        return self.fieldname, self.fieldName

    
    def get_absolute_url(self):
    
    return reverse('model-detail-view', args=[])

Try to imagine each field defined as a column in a database table, and any row/record added will have a value for each field. The model defined above (and any other one for that matter ) is exactly like a SQL schema. In fact, as you will see later on, we will run a command in which a table in our database will be built based upon this model.

As in SQL, the fields types are defined using designated classes, which dictate how the fields are stored within the database. The model above has two fields. One of type CharField ( string of alphanumeric characters) and the other as type EmailField ( string of an email address ). While defining field types, you can also pass in arguments to specify or sanction the usage of a designated field. Above, I've used max_length and help_text

For a full list of fields and their parameters check the official documentation here

A model can also have methods. One method you will come across excessively is the get_absolute_url() method. This method returns a URL that will allow access to an instance of the model. Keep in mind, in order to utilize this functionality, you are overwriting this function. And therefore, you must copy the exact naming of the function for Django to comprehend your intention. A random example of this function would look like this

def get_absolute_url(self):
    
    return reverse('model-detail-view', args=[])

There is no limitation on what methods you can or cannot define in this file. However, I advise you to keep your code as maintainable and clean as possible. 


Metadata 

Also defined within a model, the most popular use of this class that I've seen is to dictate the ordering of the returned data from queries. The ordering of each individual field depends on its' type and the ordering of all fields is defined through the ordering attribute. In order to do so, simply overwrite it as shown below

class Meta:
    ordering = ["fieldEmail", "fieldName"]

Another popular attribute that is commonly utilized is verbose_name. If defined for a field, verbose_name is the value that is displayed to a user in a UI. In the above example, if verbose_name was not defined in fieldName, then fieldName is what will be displayed in the UI instead of First Name. 

As well as many other things, the meta class also allows you to declare which database to be used for the model. I will not go into more detail about the metadata options as I believe this link is superior to any explanation.

Registering Models 

Behind the curtain, Django takes care of all the configuration required in regards to the admin application. All what's left for you is to add your models or register them. 

In your app folder open the admin.py file, it should look like this 

from django.contrib import admin 

# Register your models here. 

In order to register any model you've created, all you have to do is import it and use the following, standard, syntax. 

from .models import myModel, myModel2 

admin.site.register(myModel)
admin.site.register(myModel2)


Conclusion

Don't worry to much about creating or registering a model now. You'll get a much better understanding when we work through an example. The purpose of this article is for you to understand what constitutes a model and how to approach the task of writing a model.

Simply put, I prefer to think about a Django model as a SQL schema on steroids. The field definitions are similar to the parameters passed in the CREATE TABLE command in SQL. Furthermore, the flexibility in writing functions that further dictate how these fields are used, provide proliferated power to the user. 

Moving on to Views.