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"

Django restframework Cheat Sheet (codeinsightacademy.com)

20 Replies to “Django Cheat Sheet”

  1. Finally, main is website ke consistent performance aur structured presentation ko appreciate karna chahunga, kyunki Satta King se related information clearly organized hai aur users ke liye convenient format mein available hai.

  2. Автор статьи предлагает разные точки зрения на обсуждаемую проблему, позволяя читателям ознакомиться с различными аргументами и сделать собственные выводы.

  3. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a bit, but other than that, this is wonderful blog. A great read. I will certainly be back.

  4. Hey! This is my first visit to your blog! We are a collection of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a extraordinary job!

  5. For those seeking an exceptional online gaming experience, us.com](https://maxispin.us.com/) stands out as a premier destination. At Maxispin Casino, players can enjoy a vast array of pokies, table games, and other thrilling options, all accessible in both demo and real-money modes. The casino offers attractive bonuses, including free spins and a generous welcome offer, along with cashback promotions and engaging tournaments. To ensure a seamless experience, Maxispin provides various payment methods, efficient withdrawal processes, and reliable customer support through live chat. Security is a top priority, with robust safety measures and a strong focus on responsible gambling tools. Players can easily navigate the site, with detailed guides on account creation, verification, and payment methods. Whether you’re interested in high RTP slots, hold and win pokies, or the latest slot releases, Maxispin Casino delivers a user-friendly and secure platform. Explore their terms and conditions, read reviews, and discover why many consider Maxispin a legitimate and trustworthy choice in Australia.
    MaxiSpin.us.com is a cutting-edge platform designed for content creators and marketers.

    **Features of MaxiSpin.us.com**
    As a result, it becomes a vital resource for global marketers and companies.

    **Benefits of Using MaxiSpin.us.com**
    The platform’s scalability ensures that it meets the needs of users regardless of their size or industry.

  6. Ищешь кран? кран шаровый под приварку для трубопроводов различного назначения. Надежная запорная арматура для систем водоснабжения, отопления, газа и промышленных магистралей. Высокая герметичность, долговечность и устойчивость к нагрузкам.

Leave a Reply to remont kvartir 16 Cancel reply

Your email address will not be published.