Using Django ORM only without web server
Tags: django, sqlite, python, orm
Published: 2024-04-20 11:04:10

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
```cmd
python -m venv ormOnlyEnv
ormOnlyEnv\Scripts\activate
```

- Copy the [requirement.txt](https://github.com/ivanyu199012/16-DjangoUsedOrmOnly/blob/master/requirements.txt) to the same directory as the folder `ormOnlyEnv` and install it using below command.
```cmd
pip install -r requirements.txt
```

- Copy [manage.py](https://github.com/ivanyu199012/16-DjangoUsedOrmOnly/blob/master/manage.py) and [settings.py](https://github.com/ivanyu199012/16-DjangoUsedOrmOnly/blob/master/settings.py) to the directory and create directory `db`. Your project structure should look like as below:

![image](https://cdn.hashnode.com/res/hashnode/image/upload/v1713606041688/276bfc59-d0d4-4b7e-a4c2-81e5deedc78b.png)

### 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`
```python
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
	)
```

![image](https://cdn.hashnode.com/res/hashnode/image/upload/v1713606226101/848b1691-c1ba-42cc-a0cd-ff92054d0efb.png)

### 1.3. Generate database and table
For simplicity, in this example, we use sqlite.

- Check if there is any migration script generated and output
```cmd
python manage.py showmigrations db
```
```cmd
db
 (no migrations) --> No script is generated
```

- Generate script and output
```cmd
python manage.py makemigrations db
```
```cmd
Migrations for 'db':
  db\migrations\0001_initial.py
    - Create model Person
```

- Generate table in database and output
```cmd
python manage.py migrate
```
```cmd
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.
```cmd
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 <u>**TOP**</u> in the script file to initialize Django ORM in the beginning.

```python
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
import django
django.setup()
```

- Save the data to db by calling the model class

```python
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`

```python
##############################
## 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
```cmd
python main.py
```
```cmd
Project started!!
Saved!!
```
![image](https://cdn.hashnode.com/res/hashnode/image/upload/v1713607599225/1287bd5c-1472-42d2-bb41-9ecc4846564f.png)

## 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.😀