Logo

Django 3 : Creating our first model

Nov 23, 2020

Databases and Django

Django can interface with many databases. However, during the development of our application, we use SQLite libraries that are included in Django.

Step 1 : We will modify settings.py to set our connection to the database:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

Creating simple models

Step 2 : First, you need to define a UserProfile model. Add the following lines to the models.py in the myproject folder:

from django.db import models
class UserProfile(models.Model):
    name = models.CharField(max_length=50, verbose_name="Name")
    login = models.CharField(max_length=25, verbose_name="Login")
    password = models.CharField(max_length=100, verbose_name="Password")
    phone = models.CharField(max_length=20, verbose_name="Phone number" , null=True, default=None, blank=True)
    born_date = models.DateField(verbose_name="Born date" , null=True, default=None, blank=True)
    last_connection = models.DateTimeField(verbose_name="Date of last connection" , null=True, default=None, blank=True)
    email = models.EmailField(verbose_name="Email")
    years_seniority = models.IntegerField(verbose_name="Seniority", default=0)
    date_created = models.DateField(verbose_name="Date of Birthday", auto_now_add=True)

Activating the application

Step 3 : In order for Django to keep track of your application and be able to create database tables for its models, you have to activate it. To do this, edit the settings.py file and add blog.apps.BlogConfig to the INSTALLED_APPS setting. It should look like this:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myproject',
]

Creating and applying migrations

Step 4 : First, you will need to create an initial migration for your UserProfile model. In the root directory of your project, run the following command:

python manage.py makemigrations myproject

Step 5 : Let's take a look at the SQL code that Django will execute in the database to create the table for your model. The sqlmigrate command takes the migration names and returns their SQL without executing it. Run the following command to inspect the SQL output of your first migration:

python manage.py sqlmigrate myproject 0001

Step 6 : Let's sync your database with the new model. Run the following command to apply existing migrations:

python manage.py migrate