[PYTHON] Create a shogi game record management app using Django 2-Database settings-

Introduction

This is ** 2nd **, a memorandum of making a shogi game record management app using Django.

Work environment

The working environment this time is as follows

Also, Django's directory structure looks like this:

- kifu_app_project/
    - kifu_app_project/
        - __init__.py
        - setting.py
        - urls.py
        - wsgi.py
    - kifu_app/
        - migrations/
        - __init__.py
        - admin.py
        - apps.py
        - models.py
        - tests.py
        - views.py
    - manage.py
    - .gitignore

Contents of this article

--Database settings

Database settings

Edit settings.py

[Official document] 1 is easy to understand, so I think it is best to look at this and edit it. There is settings.py in the inner kifu_app_project, so edit it. By default, it connects to sqlite3, so change it to connect to mysql.

settings.py


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'Database name',
        'USER': 'username',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

Install MySQL library

Then enter the following command, but ...

$ python manage.py migrate
ModuleNotFound Error : No module named 'MySQLdb'

I get the error.

When I searched there, it was said that installing PyMySQL would solve it, so I will try it, but this time

$ python manage.py migrate
mysqlclient 1.3.13 or newer is required;

I got the error.

And when I looked into this error, I found the following blog. [Django: Error Resolution “raise ImproperlyConfigured (‘mysqlclient 1.3.13 or newer is required; ~) django.core.exceptions.ImproperlyConfigured: ~ ”] 2

Thanks,

Django's recommended MySQL (MariaDB) library is mysqlclient instead of PyMySQL

It seems that So, install mysqlclient with pip.

$ pip install mysqlclient

And when you run migrate again.

$ python manage.py migrate
Apply all migrations: admin ~

And it worked!

Creating a Model

This table design

I think of a Model as a table design document / template. This time, create the following table.

--Information table --Enter game information --Large Class table ――Enter the major classification of battle type --Middle Class table ――Enter the middle classification of the battle type --Small Class table --Enter a sub-classification of battle type --Kifu table ――Put the hand you actually struck

Editing models.py

First, create an Information table.

models.py


class Information(models.Model):
    date = models.DateTimeField()
    sente = models.CharField(max_length=50)
    gote = models.CharField(max_length=50)
    result = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3)])   # `validatos`Validation with(0 or more and less than 3)
    my_result = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3)])
    small_class = models.ForeignKey(SmallClass, on_delete=models.CASCADE)   #Define relations
    create_at = models.DateTimeField(auto_now_add=True)     #Automatically add time
    update_at = models.DateTimeField(auto_now=True)         #Automatically update the time

(There are some Japanese variables, but please ignore them)

For the fields that can be used, I referred to the following page. [Summary of Django database model field list] 3

What I find particularly useful about Django is that it's fairly easy to create relationships between tables. With ForeignKey (to, on_delete, ** options), you can set a many-to-one relationship (which model to relate to). This makes it easier to retrieve relevant data, such as when retrieving queries at a later date.

Similarly, define other tables.

models.py



class LargeClass(models.Model):
    name = models.CharField(max_length=10)

class MiddleClass(models.Model):
    large_class = models.ForeignKey(LargeClass, on_delete=models.CASCADE)
    name = models.CharField(max_length=10)

class SmallClass(models.Model):
    middle_class = models.ForeignKey(MiddleClass, on_delete=models.CASCADE)
    name = models.CharField(max_length=10)

class Information(models.Model):
    #~ Omitted ~

class Kifu(models.Model):
    information = models.ForeignKey(Information, on_delete=models.CASCADE)
    number = models.IntegerField(validators=[MinValueValidator(0)])
    te = models.CharField(max_length=20)

Due to the relationship (Foreign Key), if you do not write in this order, an error will occur.

Run migration

After editing models.py, execute the following command to actually perform migration. Migration is to execute SQL statements, create tables, etc. based on Model.

$ python manage.py makemigrations <app name>
Migrations for '~'
  ~\migrations\0001_initial.py
    - Create model ~
      ...~ Omitted ~

Note that this is the app name, not the project name. Hopefully you'll see the statement Create model <table name>. Also, I think that a file called 0001_initial.py is created under kifu_app_project \ kifu_app \ migrations. This file defines tables and columns based on the Model you created.

Run migrate again

Let's perform Migrate based on the Migration file created earlier and actually create a table.

$ python manage.py migrate
Applying kifu_app.0001_initial... OK

If you say "OK", you are successful!

After that, let's actually log in to mysql and check if the table is created!

Next time preview

[Django default admin site settings] 4

Recommended Posts

Create a shogi game record management app using Django 2-Database settings-
Create a shogi game record management app using Django 3 ~ Django default management site settings ~
Create a shogi game record management app using Django 4 ~ Create View ~
Create a shogi game record management app using Django 6 ~ Template division ~
Creating a Shogi Game Record Management App Using Django 1-Environment Construction-
Create a shogi game record management application using Django 5 ~ Pass DB data to Template ~
Create and deploy a Django (PTVS) app using Azure Table storage
Create a beauty pageant support app using PyLearn2
Create a Mac app using py2app and Python3! !!
Until you create a new app in Django
Try to create a Todo management site using WebSocket with Django (Swamp Dragon)
Create a Django schedule
Create a Todo app with Django REST Framework + Angular
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
Create a Todo app with the Django REST framework
Create a Todo app with Django ③ Create a task list page
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
To myself as a Django beginner (1) --Create a project app--
To myself as a Django beginner (4) --Create a memo app--
Create a Todo app with Django ⑤ Create a task editing function
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
Web App Development Practice: Create a Shift Creation Page with Django! (Design of database model)
Create a game to control puzzle & dragons drops using pygame
[Learning record] Create a mysterious dungeon game with Pyhton's Tkinter
Create a Todo app with Django ① Build an environment with Docker
Create a simple CRUD app using Django's generic class view
Create a homepage with django
DEBUG settings when using Django
Create a Django login screen
Web App Development Practice: Create a Shift Creation Page with Django! (Shift creation page)
Steps to create a Django project
Create a nested dictionary using defaultdict
Implement a Django app on Hy
Create a CRUD API using FastAPI
Create a C wrapper using Boost.Python
Create a file uploader with Django
Create a LINE Bot in Django
Web App Development Practice: Create a Shift Creation Page with Django! (Introduction)
Create a record with attachments in KINTONE using the Python requests module
Create a Todo app with Django ④ Implement folder and task creation functions