Django Cheat Sheet

Install Django

python -m pip install Django==3.1.3

Verify Django Installation

python -m django --version

List all installed python modules / packages

python -m pip list

Create new django project

django-admin startproject projectname

Run Django Project

python runserver

Create New App

python startapp newappname help

python help

MySql Database connection

    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',

open db shell with default connection

python dbshell

MySql Database Connection Troubleshoot in Windows OS
Download whl package which is compatible with your python version
Find: mysqlclient

To check whether python is 32 or 64 bit just run following command

python -m pip install mysqlclient-1.4.6-cp37-cp37m-win32.whl

open django project shell in terminal

python shell

open db shell with specific connection

python dbshell --database "connection_name"

Create model of legacy(existing) database table using inspectdb

python inspectdb --database='connection_name' table_name

Import Models in shell

from app.models import ModelName

Select data from table using Django ORM

queryset = ModelName.objects.all()

Filter data using ORM

queryset = ModelName.objects.filter(column=value)
queryset = ModelName.objects.get(column=value) #this will give you single record
queryset = ModelName.objects.filter(column__iexact=value, column2__exact=value2)
queryset = ModelName.objects.filter(col__subcol=value) #for relationship

Limit records in ORM

queryset = ModelName.objects.all()[:10]

Order by in ORM

queryset = ModelName.objects.all().order_by('columnname')
queryset = ModelName.objects.all().order_by('-columnname')
queryset = ModelName.objects.all().order_by('columnname').reverse()

Relationship in (this should be in Model which has foreign key)

foreign_key_col = models.ForeignKey(PrimaryModelName, related_name = 'related_name', on_delete = models.CASCADE, db_column = 'foreign_key_column_name')

install packages from requirements.txt for your project

python -m pip install -r requirements.txt"

Django restframework Cheat Sheet (

Leave a Reply

Your email address will not be published. Required fields are marked *