Django models using migrate

Posted under » Django on 5 May 2021

We continue where Tutorial 1 left off. We’ll setup the database, create your first model, and get a quick introduction to Django’s automatically-generated admin site

By now we should already set our mysql database settings.

Now we’ll define your models – essentially, your database layout, with additional metadata.

In our poll app, we’ll create two models: Question and Choice.

Create file polls/models.py.

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

You don't have to create the 'id' field as django will create it for you.

When we create class Question and Choice, the table name created are polls_question and polls_choice respectively. With that in mind, for an app, you only deal with the tables created for the app which in this case is the polls app.

Here, each model is represented by a class that subclasses django.db.models.Model. Each model has a number of class variables, each of which represents a database field in the model.

Each field is represented by an instance of a Field class – e.g., CharField for character fields and DateTimeField for datetimes. This tells Django what type of data each field holds.

The name of each Field instance (e.g. question_text or pub_date) is the field’s name, in machine-friendly format. You’ll use this value in your Python code, and your database will use it as the column name.

In this example, we’ve only defined a human-readable name for Question.pub_date. For all other fields in this model, the field’s machine-readable name will suffice as its human-readable name.

Some Field classes have required arguments. CharField, for example, requires that you give it a max_length. That’s used not only in the database schema, but in validation, as we’ll soon see.

A Field can also have various optional arguments; in this case, we’ve set the default value of votes to 0.

Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single Question. Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one.

It’s important to add __str__() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin.

class Question(models.Model):
# ...
def __str__(self):
return self.question_text

class Choice(models.Model):
# ...
def __str__(self):
return self.choice_text

Where "question_text" and "choice_text" is one of the fields.

That small bit of model code gives Django a lot of information. With it, Django is able to:

For autodate, the models may look like this.

import datetime
from django.db import models
from django.utils import timezone
from django.contrib import admin
from datetime import datetime

class Questionnaire(models.Model):
    student_id=models.IntegerField(default=0)
    q_id = models.CharField(max_length=2)
    rating = models.IntegerField(default=1)
    q_date = models.DateTimeField('Created', default=datetime.now)

    def __str__(self):
        return self.rating

But first we need to tell our project that the polls app is installed.

Go to settings.py

INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

This would mean, you have to go to the polls folder to create the PollsConfig class. Amend the apps.py to look like this.

from django.apps import AppConfig

class PollsConfig(AppConfig):
    name = 'polls'

Now Django knows to include the polls app. Let’s run another command.

$ python manage.py makemigrations polls

By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.

Migrations are how Django stores changes to your models (and thus your database schema) - they’re files on disk. You can read the migration for your new model if you like; it’s the file polls/migrations/0001_initial.py. They’re designed to be human-editable in case you want to manually tweak how Django changes things.

There’s a command that will run the migrations for you and manage your database schema automatically that’s called migrate - but first, let’s see the sqlmigrate command takes migration names and returns their SQL:

python manage.py sqlmigrate polls 0001

Now, run migrate again to create those model tables in your database:

python manage.py migrate

The reason that there are separate commands to make and apply migrations is because you’ll commit migrations to your version control system and ship them with your app.

Sometimes you encounter the "No migrations to apply" error. To fix this, you have to do the following.

  1. Delete the migrations file under the app name
  2. Go to the database, find the table for django_migrations, and delete all the records for the app name.
  3. run migrate again

Next, Play with Django API

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS