├── .gitignore ├── db ├── __init__.py └── models.py ├── manage.py ├── settings.py ├── main.py └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc -------------------------------------------------------------------------------- /db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | 6 | if __name__ == "__main__": 7 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /db/models.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | try: 4 | from django.db import models 5 | except Exception: 6 | print('Exception: Django Not Found, please install it with "pip install django".') 7 | sys.exit() 8 | 9 | 10 | # Sample User model 11 | class User(models.Model): 12 | name = models.CharField(max_length=50, default="Dan") 13 | 14 | def __str__(self): 15 | return self.name 16 | 17 | -------------------------------------------------------------------------------- /settings.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | 3 | # Build paths inside the project like this: BASE_DIR / 'sub_dir' 4 | BASE_DIR = Path(__file__).resolve().parent 5 | 6 | # SECURITY WARNING: Modify this secret key if using in production! 7 | SECRET_KEY = "6few3nci_q_o@l1dlbk81%wcxe!*6r29yu629&d97!hiqat9fa" 8 | 9 | # Use BigAutoField for Default Primary Key field type 10 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 11 | 12 | DATABASES = { 13 | "default": { 14 | "ENGINE": "django.db.backends.sqlite3", 15 | "NAME": BASE_DIR / 'db.sqlite3', 16 | } 17 | } 18 | 19 | 20 | """ 21 | To connect to an existing postgres database, first: 22 | pip install psycopg2 23 | then overwrite the settings above with: 24 | 25 | DATABASES = { 26 | 'default': { 27 | 'ENGINE': 'django.db.backends.postgresql_psycopg2', 28 | 'NAME': 'YOURDB', 29 | 'USER': 'postgres', 30 | 'PASSWORD': 'password', 31 | 'HOST': 'localhost', 32 | 'PORT': '', 33 | } 34 | } 35 | """ 36 | 37 | INSTALLED_APPS = ("db",) 38 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | ############################################################################ 2 | ## Django ORM Standalone Python Template 3 | ############################################################################ 4 | """ Here we'll import the parts of Django we need. It's recommended to leave 5 | these settings as is, and skip to START OF APPLICATION section below """ 6 | 7 | # Turn off bytecode generation 8 | import sys 9 | sys.dont_write_bytecode = True 10 | 11 | # Import settings 12 | import os 13 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') 14 | 15 | # setup django environment 16 | import django 17 | django.setup() 18 | 19 | # Import your models for use in your script 20 | from db.models import * 21 | 22 | ############################################################################ 23 | ## START OF APPLICATION 24 | ############################################################################ 25 | """ Replace the code below with your own """ 26 | 27 | # Seed a few users in the database 28 | User.objects.create(name='Dan') 29 | User.objects.create(name='Robert') 30 | 31 | for u in User.objects.all(): 32 | print(f'ID: {u.id} \tUsername: {u.name}') 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Django ORM Standalone 2 | ===================== 3 | 4 | ![Django](https://img.shields.io/badge/Django_ORM-Standalone-blue) 5 | ![Python](https://img.shields.io/badge/Python-yellow) 6 | 7 | Use the database components of Django without having to use the rest of Django (i.e. running a web server)! :tada: A typical use case for using this template would be if you are writing a python script and you would like the database functionality provided by Django, but have no need for the request/response functionalty of a client/server web application that Django also provides. 8 | 9 | With this project template you can write regular python scripts and use Django's excellent ORM functionality with the database backend of your choice. This makes it convienient for Djangonauts to write database driven python applications with the familiar and well polished Django ORM. Enjoy. 10 | 11 | :gear: Requirements 12 | ------------------- 13 | - Last tested successfully with Python 3.10.4 and Django 5.0.6 14 | - Create venv and pip install django to import the required modules. 15 | 16 | :open_file_folder: File Structure 17 | --------------------------------- 18 | ``` 19 | django-orm/ 20 | ├── db/ 21 | │ ├── __init__.py 22 | │ └── models.py 23 | ├── main.py 24 | ├── manage.py 25 | ├── README.md 26 | └── settings.py 27 | ``` 28 | 29 | __The main.py file is the entry point for the project, and where you start your code. You automatically get access to your models via ```from db.models import *``` 30 | Think of it like a plain old python file, but now with the addition of Django's feature-rich models.__ :smiling_face_with_three_hearts: 31 | 32 | __The db/models.py is where you configure your typical Django models.__ There is a toy user model included as a simple example. After running the migrations command in the quick setup below, a db.sqlite3 file will be generated. The settings.py file is where can swap out the sqlite3 database for another database connection, such as Postgres or AmazonRDS, if you wish. For most applications, sqlite3 will be powerful enough. But if you need to swap databases down the road, you can easily do so, which is one of the benefits of using the Django ORM. 33 | 34 | :rocket: Quick Setup 35 | -------------------- 36 | Create a folder for your project on your local machine 37 | ``` 38 | mkdir myproject; cd myproject 39 | ``` 40 | Create a virtual environment and install django 41 | ``` 42 | python -m venv venv; source venv/bin/activate; pip install django 43 | ``` 44 | Download this project template from GitHub 45 | ``` 46 | git clone git@github.com:dancaron/Django-ORM.git; cd Django-ORM 47 | ``` 48 | Initialize the database 49 | ``` 50 | python manage.py makemigrations db; python manage.py migrate 51 | ``` 52 | Run the project 53 | ``` 54 | python main.py 55 | ``` 56 | 57 | Feel free to send pull requests if you want to improve this project. 58 | 59 | :crystal_ball: Example 60 | ---------------------- 61 | After running Quick Start above: 62 | 63 | Code in db/models.py: 64 | ``` 65 | # Sample User model 66 | class User(models.Model): 67 | name = models.CharField(max_length=50, default='Dan') 68 | 69 | def __str__(self): 70 | return self.name 71 | ``` 72 | Code in main.py: 73 | ``` 74 | # Seed a few users in the database 75 | User.objects.create(name='Dan') 76 | User.objects.create(name='Robert') 77 | 78 | for u in User.objects.all(): 79 | print(f'ID: {u.id} \tUsername: {u.name}') 80 | ``` 81 | Output from command: ```python main.py``` 82 | ``` 83 | ID: 1 Username: Dan 84 | ID: 2 Username: Robert 85 | ``` 86 | 87 | :mortar_board: Django Models 88 | ---------------------------- 89 | 90 | Link: [How to Use Django Models](https://docs.djangoproject.com/en/3.1/topics/db/models/) 91 | 92 | License 93 | ------- 94 | 95 | The MIT License (MIT) Copyright (c) 2024 Dan Caron 96 | 97 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 98 | 99 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 100 | 101 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 102 | --------------------------------------------------------------------------------