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 manage.py runserver

Create New App

python manage.py startapp newappname

manage.py help

python manage.py help

MySql Database connection

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

open db shell with default connection

python manage.py dbshell

MySql Database Connection Troubleshoot in Windows OS
Download whl package which is compatible with your python version
https://www.lfd.uci.edu/~gohlke/pythonlibs/
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 manage.py shell

open db shell with specific connection

python manage.py dbshell --database "connection_name"

Create model of legacy(existing) database table using inspectdb

python manage.py 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()
print(queryset.query)
print(list(queryset))

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 models.py (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"

Leave a Reply

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