Skip to content
Django
11. Django Files Cheatsheet
Models

Default Migrations

  • Some tables schemas are default which das charfield
  • Default Database: SQLite
  • It has default admin panel.
  • When you migrate schema then your table has to be created.
  • You can create SuperUser and can see all admin panels .

When you have to make new migration at first time :

python manage.py makemigrations

After all you have to run this command :

python manage.py migrate

Model Interactions

Three-step guide to making model changes:

  • Change your models (in models.py).
  • Run python manage.py makemigrations to create migrations for those changes
  • Run python manage.py migrate to apply those changes to the database.

2.3. Make migrations

python manage.py makemigrations

Check SQL Queries

let’s see what SQL that migration would run.

The sqlmigrate command doesn’t actually run the migration on your database - instead, it prints it to the screen so that you can see what SQL Django thinks is required. It’s useful for checking what Django is going to do or if you have database administrators who require SQL scripts for changes.

python manage.py sqlmigrate polls 0001

Run Migrate

Now, run migrate again to create those model tables in your database:

python manage.py migrate

Check Issues

his checks for any problems in your project without making migrations or touching the database.

python manage.py check

Python Shell: API Playground

python manage.py shell

Model

Model are representaion of the database schema.

Create a new file named as views.py :

  • Inside sub directory of project named as textutils create a new file named as views.py.
textutils/
    textutils/
        # Create file
        views.py
    manage.py

Run on Local Server :

To run the project you have to locate path where manage.py file have.

python manage.py runserver

Create new app:

python manage.py startapp blog

Following Commands are Used

python manage.py makemigrations
 
python manage.py migrate
 
python manage.py createsuperuser
 
pip install django-crispy-forms
 
# If you are using image field in your model then you have to install this
pip install Pillow
 
 
# To see what sql commands are going to be run by this migrate command
python manage.py sqlmigrate blog 0001
 
 
# Python manage.py shell allows us to interact with our database interactively line by line
python manage.py shell

Some python shell code ->

from blog.models import Post
from django.contrib.auth.models import User
 
# Get all users
User.objects.all()  # <QuerySet [<User: irfan>, <User: TestUser>]>
 
# Get First User
User.objects.first()
 
# Get Last User
User.objects.last()
 
# Get Filter by fields
User.objects.filter(username='irfan')
 
# Get First of filter result
User.objects.filter(username='Irfan').first()
 
# Store user in a variable
user = User.objects.filter(username='Irfan').first()
 
# Get ID of user
user.id
# Get Primary Key of user which is same as id
user.pk
# Get user by id
user = User.objects.get(id=1)
 
'''
Lets create a new post which author is this user
'''
 
# Get all posts
Post.objects.all()
 
# Create post
post_1 = Post(title='Blog 1', content='First Post Content!', author=user)
# or
post_2 = Post(title='Blog 2', content='Second Post Content!', author_id=user.id)
 
# after creation of post you have to save
post_1.save()
Post.objects.all()
 
# To exit shell
exit()
 
# Store first Post in a variable
post = Post.objects.first()
 
# Now you can access all fields of post
post.content
post.date_posted
post.author
post.author.email               # grab email of author user
 
# Lets get all post created by this user
# Syntax .modelname_set
# Get all post written by a user
user.post_set   # unreadable output
user.post_set.all()
 
# Create post using post_set
user.post_set.create(title='Blog 3', content='Third Post Content!')

Writing & Reading Data via models.py in Django

1. Using dataclasses module

terminal
pip install dataclasses

2. Data in a Python Class

Run the Python Terminal:

terminal
python
python
from dataclasses import dataclass
 
@dataclass
class BlogPost:
    title: str
    content: str
python
obj = BlogPost()
# Error - Missing 2 required positional arguments: 'title' and 'content'
python
obj = BlogPost('Blog 1', 'First Post Content!')

3. Data in a Django Model Class (Django Shell)

terminal
python manage.py shell
models.py
from django.db import models
 
class Article(models.Model):
    title = models.TextField()
    content = models.TextField()

Writing

python
from articles.models import Article
obj = Article(title='Hello World', content='This is awesome')
obj.save()
print(obj.id)
 
# or
 
obj2 = Article.objects.create(title='Hello World Again', content='This is awesome')
print(obj2.id)
 
# or
obj3 = Article()
obj3.title = 'Hello World Again'
obj3.content = 'This is awesome'
obj3.save()
print(obj3.id)
  • obj.save() is used to save the object to the database.

Reading

python
Article.objects.all()
 
# or
obj = Article.objects.get(id=1)
print(obj.title)
print(obj.content)

Or Person Model

python
from dataclasses import dataclass
 
@dataclass
class Person:
    name: str
    age: int
 
p1 = Person('Irfan', 24)
p1