[Tips] Django useful commands and code snippets
By khoanc, at: 11:31 Ngày 09 tháng 9 năm 2023
Django, a high-level Python web framework, is renowned for its robustness, scalability, and rapid development capabilities. It empowers developers to create feature-rich web applications efficiently. However, mastering Django's myriad features and commands can be a daunting task, especially for newcomers.
This cheatsheet is your roadmap to conquering Django. Whether you're a seasoned developer seeking to streamline your workflow or a novice embarking on your Django journey, this concise and comprehensive reference will become your trusty companion. It condenses Django's vast ecosystem into bite-sized, actionable commands and tips that you can implement immediately.
In this article, we will take a deep dive into the world of Django Cheatsheets. We'll explore the key commands and code snippets for managing Django projects,
General Commands
python manage.py startproject projectname # Create a new project
python manage.py runserver # Run a server
python manage.py startapp appname # Create a new application
python manage.py migrate # Migrate database
python manage.py migrate app_name # Migrate database for an app
python manage.py makemigrations # Make migration script for a new change
python manage.py makemigrations app_name # Make migration script for a new change for an app
python manage.py showmigrations # Show all migrations history
python manage.py showmigrations app_name # Show all migrations history for an app
python manage.py createsuperuser # Create super user
python manage.py shell # Open Django shell
python manage.py collectstatic # Collect all static files into the static folders (default directory name is `static`)
python manage.py test # Run Django test, it looks for all test methods and test classes in the current directory.
python manage.py dbshell # Open psql commandline interface
python manage.py help # Help commands
Django Extensions commands
python manage.py shell_plus # Open Django shell_plus
python manage.py show_urls # Show all urls
python manage.py runserver_plus # Run server plus with more info
python manage.py graph_models # Output the database schema
Advance commands and code snippets
Migration tricks
python manage.py
migrate app_name zero # Migrate the app back the INITIAL migration statepython manage.py
migrate app_name 0004 --fake # Set the application migration state to the 0004 state but not actually migrate the data.
This is extremely useful when it comes to data migration testing and customization. Lets assume that there is a database migration with a new column length change (CharField). However, the database administrator already updated the database since this is urgent. Then the developer has to make a new migration and set the migration state to the new one. And he does not want to actually migrate the database. He can use --fake
option to set the database migration state.
Printing the queryset's query
attribute.
>>> queryset = User.objects.all()
>>> print(queryset.query)
SELECT "auth_user"."id", ... FROM "auth_user"
Explain query
>>> queryset = User.objects.all()
>>> print(queryset.explain)
Seq Scan on...(cost=0.00..10.40 rows=40 width=1779)
BaseModel class
from django.core import serializers
from django.db import models
from django.forms.models import model_to_dict
from django.utils import timezone
from django.utils.functional import cached_property
class BaseModel(models.Model):
class Meta:
abstract = True
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.pk}"
def to_json(self):
return serializers.serialize("json", [self])
def to_dict(self):
return model_to_dict(self)