Skip to content

11. Define the SQLite Database Schema

Katie House edited this page Sep 15, 2020 · 1 revision

In this example, our database will have one table. The database will store the user-inputted preditions, by saving the inputted features features, the classifier prediction, an auto generated ID, and the current date/time in the database.

Here is an example of the database Predictions table:

id predict_datetime sepal_length sepal_width petal_length petal_width prediction
1 09-11-2020 9:00am 5.1 3.5 1.4 0.2 setosa
2 09-11-2020 9:01am 4.9 3 1.4 0.2 setosa
3 09-11-2020 9:02am 4.7 3.2 1.3 0.2 setosa
4 09-11-2020 9:03am 4.6 3.1 1.5 0.2 setosa
5 09-11-2020 9:04am 5 3.6 1.4 0.2 setosa

Update iris/models.py to create the Predictions table:

from django.db import models
from django.utils import timezone

# Create your models here.


class Predictions(models.Model):
    # The possible predictions the model can make in the 'predictions' field
    # defined by: (<database name>, <human readible name>)
    PREDICT_OPTIONS = [
        ('setosa', 'Setosa'),
        ('versicolor', 'Versicolor'),
        ('virginica', 'Virginica')
    ]

    # Prediction table fields (or columns) are defined by creating attributes
    # and assigning them to field instances such as models.CharField()
    predict_datetime = models.DateTimeField(default=timezone.now)
    sepal_length = models.DecimalField(decimal_places=2, max_digits=3)
    sepal_width = models.DecimalField(decimal_places=2, max_digits=3)
    petal_length = models.DecimalField(decimal_places=2, max_digits=3)
    petal_width = models.DecimalField(decimal_places=2, max_digits=3)
    prediction = models.CharField(choices=PREDICT_OPTIONS, max_length=10)

Notice that id was not included. This is because by default, Django gives each model an id = models.AutoField(primary_key=True) auto incrimenting primary key.

Check here: https://www.webforefront.com/django/modeldatatypesandvalidation.html or here: https://docs.djangoproject.com/en/3.1/topics/db/models/ for more built-in field options.

7. Create the database with migrations

Although models.py determines the database schema, you must migrate the database for these changes to be in affect.

You must migrate in the following scenarios:

  1. Adding a Model (aka Table)
  2. Adding a Field (aka Column in Table)
  3. Removing a Field
  4. Changing a Field Schema
python3 manage.py makemigrations
python3 manage.py migrate
Clone this wiki locally