Read existing tables from MySQL database in Django Models

MySQL tables need to have primary key assigned to one of the columns. Otherwise, django will try to find an ‘id’ column in the table.

Run the code below to let django scan the database and create models.py
python manage.py inspectdb > models.py

Sample of using models to call values from the database:
queryset = class_name_in_models.objects.all()
test = queryset.values_list('col_name')

Set Up Local Environment for MySQL (Python + Django + XAMPP)

Set up local database – XAMPP
XAMPP has the full package for Apache + MySQL. “phpMyAdmin” is used for database management, which will be useful when import local database to web db (ex. pythonanywhere.com)

Install python package to interact with MySQL database
Option 1: import MySQLdb
pip install mysql-python (python 2.7) / pip install mysqlclient (python3.x)
Option 2: import mysql.connector
pip install mysql-connector-python

Continue reading