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
- Copy the requirement.txt to the same directory as the folder
ormOnlyEnv
and install it using below command.
pip install -r requirements.txt
- Copy manage.py and settings.py to the directory and create directory
db
. Your project structure should look like as below:
1.2. Create Model class
- Create
models.py
under directorydb
. Place your own model (data stored to db) inmodels.py
. We use the classPerson
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
)
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
db
(no migrations) --> No script is generated
- Generate script and output
python manage.py makemigrations db
Migrations for 'db':
db\migrations\0001_initial.py
- Create model Person
- Generate table in database and output
python manage.py migrate
Migrations for 'db':
db\migrations\0001_initial.py
- Create model Person
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
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()
- 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!!")
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!!")
Run the files and you can see the record is saved to db
python main.py
Project started!!
Saved!!
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)