[PYTHON] It's too easy to use an existing database with Django

Purpose

From an acquaintance who read the article the other day "Then, if you already have a DB in operation, can you attach Django later?" There was a selfish request, so I also verified it.

From the conclusion, it was possible. Moreover, it's easy. Obviously, it seems that the supported database products and versions are limited to some extent. This area will be helpful.

manner

I will use the application from the previous article again, but delete the table on the database side. Now you have the Django code, but the database isn't ready yet.

Status quo confirmation

Although the settings are written in settings.py, the database side is not ready. If you try to start the server in this state, it will look like this. Well that's right.

> python manage.py runserver

~Omission~
django.db.utils.OperationalError: FATAL:  database "webshopping" does not exist

Prepare the database

Prepare a suitable database and table to make it look like an existing database.

> psql -U postgres -W
Password for user postgres:********

postgres=# CREATE DATABASE newshopping;
CREATE DATABASE

postgres=# \c newshopping;
newshopping=# CREATE TABLE items(
                item_name TEXT PRIMARY KEY,
                price INTEGER
              );
CREATE TABLE

In addition, throw in appropriate data.

postgres=# INSERT INTO items VALUES('Fragile window glass', 50000);
INSERT 0 1
postgres=# INSERT INTO items VALUES('Hard-to-break window glass', 99000);
INSERT 0 1

newshopping=# SELECT * FROM items;
     item_name      | price
--------------------+-------
Fragile window glass| 50000
Hard-to-break window glass| 99000

(2 lines)

So the data seems to be inserted firmly.

Check settings.py

If you change your database product, you need to change settings.py. Please refer to this area for how to write the ENGINE part. For postgresql, the following is OK. The NAME part is the distinguished name of the database. I created it with the name newshopping earlier, so I will write it exactly as it is. There is nothing special about the other parameters. All you have to do is write the user name, password, and host name to access.

settings.py


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'newshopping',
        'USER': 'your_db_username',
        'PASSWORD': 'your_db_password',
        'HOST': 'localhost',
        'PORT': '',
    }
}

Link using django tools

The URL of here posted at the beginning has detailed usage, but it is the same as the existing database. There is a tool that will make adjustments for you. How to start is like this.

> python manage.py inspectdb

class Items(models.Model):
    item_name = models.TextField(primary_key=True)
    price = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'items'

If the settings.py settings are successful, the code of the class corresponding to Model will be returned as shown above. You can paste this into your Models.py or write it directly to your existing Models.py as follows:

> python manage.py inspectdb >> models.Path to py/models.py

If you set it to ">", it will be overwritten, so it is recommended to set it to ">>". After that, it is better to comment out the existing description that is no longer needed.

Looking at models.py ...

models.py


# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey has `on_delete` set to the desired behavior.
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models


class Items(models.Model):
    item_name = models.TextField(primary_key=True)
    price = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'items'

The class definition has been added successfully!

Final adjustment with existing code

Well, I made a mistake in naming the table. The code was passed through the "Item" class, but the automatically generated Model class is "Items". This is because the table name in the database is "items".

But it's okay. After all, since it is a class definition, there is no problem even if you change this class name. So, I played with the class definition part a little.

models.py


# ~Abbreviation~
class Item(models.Model):
# ~Abbreviation~

Operation check

Now, let's start the server and check the operation.

> python manage.py runserver

There seems to be no problem at all! image.png

Conclusion

Recommended Posts

It's too easy to use an existing database with Django
Browse an existing external database with Django
[Introduction to WordCloud] It's easy to use even with Jetson-nano ♬
Use Gentelella with django
Easy to use Flask
Use LESS with Django
Easy to use SQLite3
Use MySQL with Django
An easy way to create an import module with jupyter
It's too troublesome to display Japanese with Vim's python3.
Deploy an existing app with docker + pyenv-virtualenv + uwsgi + django
Preparing to use Ansible on an existing Linux server
Building an environment to use CaboCha with google colaboratory
It's too easy to access the Twitter API with rauth and I have her ...
Easy to use Nifty Cloud API with botocore and python
Create an API with Django
Easy to make with syntax
I'm trying to create an authentication / authorization process with Django
Rename an existing Django application
Easy to use E-Cell 4 Intermediate
Use prefetch_related conveniently with Django
I want to use an external library with IBM Cloud Functions
[Python] Explains how to use the format function with an example
How to use an external editor for Python development with Grasshopper
Prepare an environment to use OpenCV and Pillow with AWS Lambda
I compared while reading the documentation to use Jinja2 with Django
Steps to develop Django with VSCode
Python: How to use async with
Use Azure SQL Database with SQLAlchemy
Load Django modules with an interpreter
Django1.11.1 Image uploader Easy to stumble
How to use virtualenv with PowerShell
Common html to rent with Django
Easy to install pyspark with conda
How to get started with Django
How to use FTP with Python
Easy to use E-Cell 4 Advanced Edition
Easy to use Jupyter notebook (Python3.5)
[Django] Use MessagePack with Django REST framework
Easy to draw graphs with matplotlib
Note: Send an email with Django
Use boto3 to mess with S3
How to authenticate with Django Part 2
How to authenticate with Django Part 3
[Python Tutorial] An Easy Introduction to Python
Use Unicode 6.0 emoji with django / MySQL
[AWS] [GCP] I tried to make cloud services easy to use with Python
How to do arithmetic with Django template
Step notes to get started with django
[Introduction to mediapipe] It's really easy to move ♬
How to use ManyToManyField with Django's Admin
How to use OpenVPN with Ubuntu 18.04.3 LTS
How to use Cmder with PyCharm (Windows)
[Django] Give an initial value to ChoiceField
[Introduction to Python] Let's use foreach with Python
How to use Ass / Alembic with HtoA
Easy way to use Wikipedia in Python
How to use Japanese with NLTK plot
How to use jupyter notebook with ABCI
Create an update screen with Django Updateview
Use Ghost.py as an alternative to PhantomJS