DEV Community

Cover image for Using Django ORM only without web server
Ivan Yu
Ivan Yu

Posted on • Originally published at ivanyu2021.hashnode.dev

Using Django ORM only without web server

Django is a great framework, but sometimes you just want to use its ORM without web server function. This blog will introduce how to do it.

1. Step

1.1. Setup environment

  • Create a virtual environment named ormOnlyEnv and then activate it
python -m venv ormOnlyEnv
ormOnlyEnv\Scripts\activate
Enter fullscreen mode Exit fullscreen mode
  • Copy the requirement.txt to the same directory as the folder ormOnlyEnv and install it using below command.
pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode
  • Copy manage.py and settings.py to the directory and create directory db. Your project structure should look like as below:

image

1.2. Create Model class

  • Create models.py under directory db. Place your own model (data stored to db) in models.py. We use the class Person as an example.

models.py

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

## Create your models here.
class Person(models.Model):

    name = models.CharField(
        max_length=50,
        blank=False
    )
    age = models.IntegerField()
    birth_date = models.DateTimeField(
        blank=False
    )
Enter fullscreen mode Exit fullscreen mode

image

1.3. Generate database and table

For simplicity, in this example, we use sqlite.

  • Check if there is any migration script generated and output
python manage.py showmigrations db
Enter fullscreen mode Exit fullscreen mode
db
 (no migrations) --> No script is generated
Enter fullscreen mode Exit fullscreen mode
  • Generate script and output
python manage.py makemigrations db
Enter fullscreen mode Exit fullscreen mode
Migrations for 'db':
  db\migrations\0001_initial.py
    - Create model Person
Enter fullscreen mode Exit fullscreen mode
  • Generate table in database and output
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode
Migrations for 'db':
  db\migrations\0001_initial.py
    - Create model Person
Enter fullscreen mode Exit fullscreen mode

1.3.1. Remark

If you have update models.py, remember to run following commands again to synchronize database.

python manage.py makemigrations db
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

2. Create your own script

  • Here is the most IMPORTANT point, place the following code at the TOP in the script file to initialize Django ORM in the beginning.
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
import django
django.setup()
Enter fullscreen mode Exit fullscreen mode
  • Save the data to db by calling the model class
import datetime
from db.models import Person

print("Project started!!")
person = Person()
person.name = 'John Doe'
person.age = 30
person.birth_date = datetime.datetime(1963, 2, 5)
person.save()
print("Saved!!")
Enter fullscreen mode Exit fullscreen mode

Whole file main.py

##############################
## Django specific settings (Please this BEFORE import model class)
##############################
import django
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
django.setup()
##############################

import datetime
from db.models import Person

print("Project started!!")
person = Person()
person.name = 'John Doe'
person.age = 30
person.birth_date = datetime.datetime(1963, 2, 5)
person.save()
print("Saved!!")
Enter fullscreen mode Exit fullscreen mode

Run the files and you can see the record is saved to db

python main.py
Enter fullscreen mode Exit fullscreen mode
Project started!!
Saved!!
Enter fullscreen mode Exit fullscreen mode

image

3. Git repo

https://github.com/ivanyu199012/16-DjangoUsedOrmOnly/

4. Reason I wrote this blog

Recently, I needed to build a python script to save some records to database. I considered manually creating tables and coding sql insert command, but this would cost a lot of times.

I remembered that in the past, I used Django ORM only without the web server to save records to database, so I decided to use it.

I forgot how to do it, so I spent some time to test and refresh my memory and finally I succeed it. This blog is wrote so that in the future, if I forgot how to do it, I can check this blog and hope it can also help the others.

Thanks for reading.😀

Top comments (0)