Intro
Django was my go to framework for anything. I still Love Django framework. I thought, nicest thing was Django's ORM. So, I try here to integrate Django ORM with FastAPI.
Content
I created a folder for project first.
mkdir django.orm.with.fastapi
cd django.orm.with.fastapi
Then I did a few django project specific bootstrapping here with following commands. That dot (ie. ".") at the end describe where the project is created. Rest you probably know or you can search and understand or ask LLM easily.
django-admin startproject config .
python manage.py startapp app1
# Now add app1 to INSTALLED_APPS
INSTALLED_APPS = [
...
"app1",
]
# end of settings.py file editing
python manage.py migrate
Now project folder is something like this. Kindly note, app.py is a FastAPI file, I created.
✦ ❯ tree | grep -v pyc
.
├── app1
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── app.py
├── config
│ ├── asgi.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── db.sqlite3
├── manage.py
└── requirements.txt
Now add a model into app1/models.py
class Todo(models.Model):
task = models.CharField(max_length=200)
is_done = models.BooleanField(default=False)
def __str__(self):
return self.task
And here is the minimalist app.py (FastAPI file)
from typing import Union
from fastapi import FastAPI
app = FastAPI()
items = []
@app.get("/")
def read_root():
return {"Hello": "World"}
These lines are crux of this article
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
django.setup()
Now read updated FastAPI and see how it utilize the Django ORM for Creating and Listing the Todo Modal Instances into DB.
import os
import django
from typing import Union
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
django.setup()
from fastapi import FastAPI
from app1.models import Todo
app = FastAPI()
items = []
@app.get("/{name}")
def read_root(name: str) -> Union[str, dict]:
return {"Hello": name}
@app.get("/todos/")
def get_todos():
todos = Todo.objects.all()
return [{"id": todo.pk, "task": todo.task, "is_done": todo.is_done} for todo in todos]
@app.post("/todos/")
def create_todo(task: str):
new_todo = Todo(task=task)
new_todo.save()
return {"id": new_todo.pk, "task": new_todo.task, "is_done": new_todo.is_done}
Tip
If you're stuck at reproducing this. Have a look at github repo in reference section of this article. Github contains a branch async-create-and-list with async version of the same.
Reference
https://fastapi.tiangolo.com/#create-it
https://www.sahilfruitwala.com/blog/fastAPI-with-Django-ORM
https://github.com/ajeebkp23/django.orm.with.fastapi
Top comments (0)