Creating the models

Now we will create a simple Game model that we will use to represent and persist games. Open the games_service/games/models.py file. The following lines show the initial code for this file, with just one import statement and a comment that indicates we should create the models:

from django.db import models 
 
# Create your models here. 

Replace the code for the games_service/games/models.py file with the following lines. The new code creates a Game class, specifically, a Game model in the games/models.py file. The code file for the sample is included in the restful_python_2_05_01 folder, in the Django01/games_service/games/apps.py file:

from django.db import models 
 
 
class Game(models.Model): 
    created_timestamp = models.DateTimeField(auto_now_add=True) 
    name = models.CharField(max_length=200, default='') 
    release_date = models.DateTimeField() 
    esrb_rating = models.CharField(max_length=150, default='') 
    played_once = models.BooleanField(default=False) 
    played_times = models.IntegerField(default=0) 
 
    class Meta: 
        ordering = ('name',) 

The Game class is a subclass of the django.db.models.Model superclass. Each attribute declared within the Game class represents a database column or field. Django automatically adds an auto-increment integer primary key column named id when it creates the database table related to the model. We specified the field types, maximum lengths, and defaults for many attributes.

The Game class declares an inner class named Meta that declares an ordering attribute and sets its value to a tuple of a string whose first value is the 'name' string, indicating that, by default, we want the results ordered by the name attribute in ascending order.

By default, Django has its ORM configured to use an SQLite database. In this example, we will be working with this default configuration.

Then, it is necessary to create the initial migration for the new Game model we recently coded. Run the following Python script:

    python manage.py makemigrations games

The following lines show the output generated after running the previous command:

    Migrations for 'games':
      games/migrations/0001_initial.py
        - Create model Game

The output indicates that the games_service/games/migrations/0001_initial.py file includes the code to create the Game model. The following lines show the code for this file that was automatically generated by Django. The code file for the sample is included in the restful_python_2_05_01 folder, in the Django01/games_service/games/migrations/0001_initial.py file:

# Generated by Django 2.1.4 on 2018-10-24 15:45 
 
from django.db import migrations, models 
 
 
class Migration(migrations.Migration): 
 
    initial = True 
 
    dependencies = [ 
    ] 
 
    operations = [ 
        migrations.CreateModel( 
            name='Game', 
            fields=[ 
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 
                ('created_timestamp', models.DateTimeField(auto_now_add=True)), 
                ('name', models.CharField(max_length=200)), 
                ('release_date', models.DateTimeField()), 
                ('esrb_rating', models.CharField(max_length=150)), 
                ('played_once', models.BooleanField(default=False)), 
                ('played_times', models.IntegerField(default=0)), 
            ], 
            options={ 
                'ordering': ('name',), 
            }, 
        ), 
    ] 

The code defines a subclass of the django.db.migrations.Migration superclass named Migration that defines an operation that creates the Game model's table. Now, run the following Python script to apply all the generated migrations:

    python manage.py migrate

The following lines show the output generated after running the previous command:

    Operations to perform:
      Apply all migrations: admin, auth, contenttypes, games, sessions
    Running migrations:
      Applying contenttypes.0001_initial... OK
      Applying auth.0001_initial... OK
      Applying admin.0001_initial... OK
      Applying admin.0002_logentry_remove_auto_add... OK
      Applying admin.0003_logentry_add_action_flag_choices... OK
      Applying contenttypes.0002_remove_content_type_name... OK
      Applying auth.0002_alter_permission_name_max_length... OK
      Applying auth.0003_alter_user_email_max_length... OK
      Applying auth.0004_alter_user_username_opts... OK
      Applying auth.0005_alter_user_last_login_null... OK
      Applying auth.0006_require_contenttypes_0002... OK
      Applying auth.0007_alter_validators_add_error_messages... OK
      Applying auth.0008_alter_user_username_max_length... OK
      Applying auth.0009_alter_user_last_name_max_length... OK
      Applying games.0001_initial... OK
      Applying sessions.0001_initial... OK
  

After we run the previous command, we will notice that the root folder for our games_service project now has a db.sqlite3 file. We can use the SQLite command line or any other application that allows us to easily check the contents of the SQLite database to check the tables that Django generated.

In macOS and most modern Linux distributions, SQLite is already installed, and therefore, you can run the sqlite3 command-line utility. However, in Windows, if you want to work with the sqlite3.exe command-line utility, you will have to download and install SQLite from its web page http://www.sqlite.org and add the path in which the executable file is located to the PATH environment variable.

Run the following command to list the generated tables. The code file for the sample is included in the restful_python_2_05_01 folder, in the Django01/cmd/list_sqlite3_tables.txt file:

    sqlite3 db.sqlite3 ".tables"

The following lines show the output for the previous command:

    auth_group                  django_admin_log          
    auth_group_permissions      django_content_type       
    auth_permission             django_migrations         
    auth_user                   django_session            
    auth_user_groups            games_game                
    auth_user_user_permissions

Run the following command to retrieve the SQL used to create the games_game table. The code file for the sample is included in the restful_python_2_05_01 folder, in the Django01/cmd/retrieve_sql_sqlite3_games_game_table.txt file:

    sqlite3 db.sqlite3 ".schema games_game"

The following command will allow you to check the contents of the games_game table after we compose and send HTTP requests to the RESTful API and make CRUD operations to the games_game table. The code file for the sample is included in the restful_python_2_05_01 folder, in the Django01/cmd/check_contents_sqlite3_games_game_table.txt file:

    sqlite3 db.sqlite3 "SELECT * FROM games_game ORDER BY name;"

Instead of working with the SQLite command-line utility, you can use a GUI tool to check the contents of the SQLite database. DB Browser for SQLite is a useful multiplatform and free GUI tool that allows us to easily check the database contents of an SQLite database in macOS, Linux, and Windows. You can read more information about this tool and download its different versions from http://sqlitebrowser.org. Once you have installed the tool, you just need to open the db.sqlite3 file and you can check the database structure and browse the data for the different tables. You can use also the database tools included in your favorite IDE to check the contents for the SQLite database.

The SQLite database engine and the database file name are specified in the games_service/games_service/settings.py Python file. The following lines show the declaration of the DATABASES dictionary that contains the settings for all the databases that Django uses. The nested dictionary maps the database named default with the django.db.backends.sqlite3 database engine and the db.sqlite3 database file located in the BASE_DIR folder (games_service):

DATABASES = { 
    'default': { 
        'ENGINE': 'django.db.backends.sqlite3', 
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 
    } 
} 

After we have executed the migrations, the SQLite database will have the following tables:

  • auth_group
  • auth_group_permissions
  • auth_permission
  • auth_user
  • auth_user_groups
  • auth_user_user_permissions
  • django_admin_log
  • django_content_type
  • django_migrations
  • django_session
  • games_game

The games_game table persists the Game class, specifically, the Game model, in the database. Django's integrated ORM generated the games_game table based on our Game model. The games_game table has the following rows (also known as fields) with their SQLite types, all of them not nullable:

  • id: The integer primary key, an autoincrement row
  • created_timestamp: datetime
  • name: varchar(200)
  • release_date: datetime
  • Esrb_rating: varchar(150)
  • played_once: bool
  • played_times: integer

The following lines show the SQL creation script that Django generated when we executed the migrations:

CREATE TABLE IF NOT EXISTS "games_game" ( 
    "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,  
    "created_timestamp" datetime NOT NULL,  
    "name" varchar(200) NOT NULL,  
    "release_date" datetime NOT NULL,  
    "esrb_rating" varchar(150) NOT NULL,  
    "played_once" bool NOT NULL,  
    "played_times" integer NOT NULL); 

Django generated the additional tables that it requires to support the web framework and the authentication features that we will use later.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.96.146