0% found this document useful (0 votes)
165 views55 pages

Django Request Debugging Guide

The document provides an overview of important concepts in Django, including how to print the request object and its attributes using the dir() function, the significance of raw strings in URLs, and the methods for importing functions or classes in Python. It also explains the usage of the breakpoint() function for debugging and the locals() function for inspecting local variables. Key practices include avoiding logging sensitive information, using raw strings to handle special characters, and understanding relative and absolute imports.

Uploaded by

SATYAM SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
165 views55 pages

Django Request Debugging Guide

The document provides an overview of important concepts in Django, including how to print the request object and its attributes using the dir() function, the significance of raw strings in URLs, and the methods for importing functions or classes in Python. It also explains the usage of the breakpoint() function for debugging and the locals() function for inspecting local variables. Key practices include avoiding logging sensitive information, using raw strings to handle special characters, and understanding relative and absolute imports.

Uploaded by

SATYAM SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Django: Most Important Points to Note and Remem-

ber...

How to Print the Request Object in Django


Understanding dir() Function
dir() ek built-in Python function hai jo kisi bhi object ke sare attributes (methods, properties, etc.)
list kar deta hai.
Django me kyu use karte hain? Jab request object ke andar kya-kya data hai yeh pata nahi hota,
tab dir(request) use karke available attributes dekh sakte hain.
Example Usage:
attributes = dir(request)
print("Request Attributes:", attributes)

Practical Example: Exploring Request Attributes


Agar aap dir(request) run karenge, to yeh output milega:
['COOKIES', 'FILES', 'GET', 'POST', 'META', 'body', 'headers', 'method', 'path', ...]

Explanation:
• GET - Query parameters ko store karta hai (e.g., ?search=django).

• POST - User ke form data ko store karta hai.


• headers - HTTP headers jaise authorization token ko contain karta hai.
• body - Raw request body hota hai (JSON data APIs ke liye useful hota hai).

Using Middleware to Print Request Attributes


Code:
class DebugMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):


print("Request Attributes:", dir(request)) # Debugging request attributes
return self.get_response(request)

Warning: Sensitive information jaise passwords ya authentication tokens ko production logs me


print mat karein.
Extracting Specific Request Data
Aap request object se specific data aise extract kar sakte hain: Code:
# Query parameters ko extract karna (e.g., ?search=django)
print("Query Params:", request.GET)

# Form data (POST requests ke liye)


print("Form Data:", request.POST)

# Headers extract karna (e.g., Authorization header)


print("Headers:", request.headers)

# Raw request body extract karna (JSON data ke liye)


print("Body:", request.body.decode('utf-8'))

1
Expected Output
Agar request ke headers aur body print karenge, to kuch aisa output milega:
Query Params: {'search': 'django'}
Form Data: {'username': 'admin', 'password': '1234'}
Headers: {'Authorization': 'Bearer abc123'}
Body: '{"task": "Learn Django"}'

Summary
• dir(request) Django ke request object ke attributes explore karne ke liye use hota hai.
• Debugging aur request ka data samajhne ke liye useful hai.
• Sensitive data ko production me log mat karein.
• Common attributes: GET, POST, headers, body, etc.

=============================== ===============================
Raw Strings in Python URLs
Raw strings in Python URLs (like r’string’) are used to handle special characters (such as backslashes
) properly. Let’s understand this in Hinglish with a small example:

Raw String r ka use kya hai?


Python me jab hum kisi string ke aage r lagate hain, usse wo raw string ban jati hai. Raw string ka
matlab hota hai ki Python us string me escape sequences (\n, \t, etc.) ko special meaning nahi
dega.
Example: Agar hum kisi URL me backslash (
) use karte hain, toh Python escape sequences ko misinterpret kar sakta hai. Raw string se yeh problem
solve ho jati hai.

URL.py example with raw string (r)


from django.urls import path
from . import views

urlpatterns = [
path(r'home\details', views.home_details, name='home_details'),
]

Explanation:
- r’home
details’: Yaha r ensure karta hai ki
d ko Python as-is treat kare. Without r, Python
d ko escape sequence (digit regex) samajh sakta hai. - Agar r nahi diya, toh:
path('home\details', views.home_details, name='home_details')

- Yaha
d ko Python regex samajh lega, jo URL ko break karega ya galat behavior karega. - Aapko "SyntaxError"
ya "URL not found" ka error mil sakta hai.

Without raw string example:


path('home\details', views.home_details, name='home_details')

- Yaha
d Python ke liye escape sequence ban gaya (jo regex match karega numbers ke liye), toh URL ka
actual path galat ho jayega.

2
Output difference:
1. With r (Correct behavior): URL correctly match karega /home/details.
2. Without r (Incorrect behavior): Python
d ko misinterpret karega as regex for digits, and URL break ho sakta hai.

Summary in Hinglish:
• Raw string (r’string’) ka use special characters ko avoid karne ke liye hota hai, jaise backslash (
).
• Agar r nahi diya URL me, toh escape sequences galat behavior karenge, jaise regex misinterpreta-
tion.
• Yeh practice URLs, file paths, ya regex me backslash handle karne ke liye mandatory
hai.

=============================== ===============================
How to Import Function or Class
Understanding the Import Syntax:
Python me jab aap from .models import DeveloperTask dekhte hain, to iska matlab hota hai ki aap
ek relative import kar rahe hain. Chaliye ise break down karte hain:
from .models import DeveloperTask

• from .models:
– Yaha . (dot) ka matlab hai current directory, matlab jo file chal rahi hai uske folder me
hi models module ko dhundo.
– Ye relative import hai jo ek package ke andar modules ko import karne ke liye use hota hai.

• import DeveloperTask:
– Yeh models.py file ke andar se DeveloperTask class ko import karega.

Example Folder Structure (Relative Import)


Maan lijiye aapke paas yeh folder structure hai:
my_project/

app/
__init__.py
models.py
views.py
tasks.py
manage.py

Agar aap views.py ke andar ho aur models.py se DeveloperTask import karna chahte ho, toh aap
likhoge:
# In views.py
from .models import DeveloperTask # From models.py (same folder as views.py)

How to Import From a Different Folder


Agar models.py kisi aur folder me ho, toh usko import karne ke liye do tareeke hain: relative imports
aur absolute imports.

3
1. Relative Imports (For Same Package Structure)
Agar structure kuch aisa hai:
my_project/

app/
__init__.py
models/
models.py
views.py
tasks.py
manage.py

Aur aapko views.py me models/models.py se DeveloperTask import karna hai, toh aap likh sakte
hain:
# In views.py
from .models.models import DeveloperTask # From models/models.py (relative to the current
folder)

2. Absolute Imports (From Any Folder in the Project)


Agar aap ek specific folder se import karna chahte hain bina relative import ka use kiye, toh absolute
import ka use karein:
# In views.py
from app.models.models import DeveloperTask # Absolute import from app/models/models.py

Yaha app project ka top-level folder hai, aur models.models uska path hai jo models.py tak le jaata
hai.
3. Importing from a Folder Outside the Project
Agar aapko kisi aur folder se import karna hai jo aapke Django project se bahar hai, toh aapko sys.path
modify karna padega:
import sys
sys.path.append('/path/to/your/folder')

from mymodule import MyClass

Par ye tareeka recommended nahi hai Django applications ke liye. Best practice hai ki aap apne
project ka structure theek se organize karein.
Summary
• Relative Imports: from .models import DeveloperTask ka use karein agar same folder me ho.
• Absolute Imports: from app.models.models import DeveloperTask use karein agar kisi aur
folder se import karna ho.
• Subfolder Imports: from .models.models import DeveloperTask ka use karein agar module
kisi subfolder me ho.

Relative imports internal structure ke liye useful hote hain, jabki absolute imports clarity aur read-
ability ke liye better hote hain.
=============================== ===============================
Understanding the breakpoint() Function for Debugging in Python
What is breakpoint()?
The breakpoint() function is a built-in function in Python that pauses the execution of your code at
the point where it’s called and opens an interactive debugging session. This helps you inspect the state
of the program, check variable values, and step through the code to find issues.
When you call breakpoint(), it activates the Python Debugger (pdb) and gives you access to
several commands to inspect and control the execution flow. For example, you can step through the code
line by line, print variables, or continue execution.

4
Example 1: Simple Example with breakpoint()
Let’s go through a simple Python function to see how breakpoint() works.
def calculate_sum(a, b):
result = a + b
breakpoint() # Execution will stop here
return result

x = 5
y = 3
sum_result = calculate_sum(x, y)
print(f"Sum␣is:␣{sum_result}")

How it works:
1. Call the Function: When you run the script, the function calculate sum(x, y) is called with
x=5 and y=3.
2. Breakpoint: The execution will stop right at breakpoint() inside the function.
3. Debugging: Once the breakpoint is hit, Python will pause execution, and you’ll enter the debug-
ger. You can then interact with the program to inspect variables and control the flow.
4. Continue Execution: After inspecting the values and stepping through the code, you can continue
executing the program.
What happens in the terminal:
When you run the code, it will output the following at the point where the execution is paused:
> script.py(5)calculate_sum()
-> return result
(Pdb)
Here, (Pdb) indicates that you are in the Python Debugger. The code execution is paused at the line
return result.
At this point, you can use the following debugging commands:

• p <variable>: Prints the value of a variable. For example:


(Pdb) p a
5
(Pdb) p b
3
(Pdb) p result
8

• n (next): Move to the next line of code.


(Pdb) n
> script.py(6)<module>()

• c (continue): Continue executing the code until the next breakpoint or the end of the program.
(Pdb) c

• q (quit): Exit the debugger and stop the execution of the program.
(Pdb) q

After continuing with c, the program will run the rest of the code and output:
Sum is: 8

5
Example 2: Debugging a More Complex Scenario
Let’s see an example where you want to debug a function that might have an error, and you’ll use
breakpoint() to inspect variables and understand where it fails.
def divide_numbers(a, b):
breakpoint() # Execution will stop here
return a / b

num1 = 10
num2 = 0 # This will cause a ZeroDivisionError
result = divide_numbers(num1, num2)
print(f"Result␣is:␣{result}")

How it works:
1. The divide numbers function is called with num1 = 10 and num2 = 0.

2. The program hits the breakpoint() and pauses.


3. You can inspect the values of a and b before the division happens, and check if the division will
lead to an error.
4. After inspecting the variables, you can choose to continue or step through the code to see what
happens when it tries to divide by zero.

When you run the code, it will stop at the breakpoint, and you can inspect the values of a and b:

> script.py(3)divide_numbers()
-> return a / b
(Pdb) p a
10
(Pdb) p b
0

Here, you see that b is 0, which will cause a ZeroDivisionError when the code executes the line
return a / b.
At this point, you can either choose to continue (c) or step (n). If you continue, it will raise the error
as expected:

(Pdb) c
Traceback (most recent call last):
File "script.py", line 7, in <module>
result = divide_numbers(num1, num2)
File "script.py", line 4, in divide_numbers
return a / b
ZeroDivisionError: division by zero

This allows you to catch and understand errors while debugging before the program crashes.
Summary of breakpoint() Use
• Setting the Breakpoint: Place breakpoint() wherever you want to stop the code execution.
• Inspecting Variables: Use commands like p <variable> to check variable values.
• Step Through the Code: Use commands like n (next) to step through the code, and c (continue)
to run the code until the next breakpoint.

• Examine the Stack: Use bt (backtrace) to examine the call stack and trace the flow of execution.
• Exit the Debugger: Use q to quit the debugger and stop execution.

6
Useful Debugger Commands:
• n — Execute the next line of code.
• s — Step into a function.
• c — Continue execution until the next breakpoint.
• p <var> — Print the value of a variable.
• q — Quit the debugger and exit the program.
• bt — Print the call stack to see where the error occurred.
By using breakpoint(), you can pause your program’s execution, inspect the state of variables, and
debug issues interactively.
=============================== ===============================
locals() Python me: Ek Overview
locals() ek built-in function hai jo ek dictionary return karta hai jo current local symbol table ko
represent karta hai. Yeh symbol table saari local variables aur unki values ko store karta hai jahan
locals() call hota hai.

Syntax
locals()

• Kya return hota hai?: Ek dictionary jisme keys variable names (as strings) hote hain aur values
unka corresponding data hota hai.

Kab Use Karein locals()?


1. Debugging: Current local scope ke saare variables dekhne ke liye.
2. Dynamic Code Execution: Runtime me variables modify ya interact karne ke liye.
3. Template Rendering: Saare local variables ek function ya template ko pass karne ke liye (Djan-
go/Jinja2 me useful).
4. Introspection: Program ki state analyze ya log karne ke liye.

Examples
1. Debugging with locals()
Jab debugging karni ho, to locals() ka use karke saare variables print kar sakte hain.
def debug_example():
x = 10
y = "hello"
z = [1, 2, 3]
print(locals()) # {'x': 10, 'y': 'hello', 'z': [1, 2, 3]}

2. Modifying Local Variables Dynamically


Directly locals() ko modify karna achha practice nahi hai, lekin testing/debugging ke liye useful ho
sakta hai.
def dynamic_example():
a = 5
b = 10
local_vars = locals()
print(local_vars) # {'a': 5, 'b': 10}

# Dynamically modifying values


local_vars['a'] = 20 # Yeh change actual variable pe effect nahi karega
print(a) # Output: 5 (not affected)

7
3. Variables ko Templates me Pass Karna
Django ya Jinja2 frameworks me saare local variables ko template me bhejne ke liye use hota hai.
def template_example():
name = "John"
age = 30
return render_template("profile.html", **locals()) # Passes {'name': 'John', 'age': 30}

4. Logging State
Troubleshooting ya analysis ke liye saare local variables log karna.
def log_example():
user_id = 123
action = "login"
print(f"Local␣variables:␣{locals()}")
# Output: Local variables: {'user_id': 123, 'action': 'login'}

5. Interactive Debugging
breakpoint() ya pdb ke sath locals() ka use karke variables inspect kar sakte hain.
def interactive_debug():
x = 42
y = "debug"
breakpoint() # Interactive debugging mode enter karega

Debugging session me:

(Pdb) locals()
{’x’: 42, ’y’: ’debug’}

Limitations
• Read-Only in Function Scope: Function ke andar, locals() ka dictionary modify karne se
actual variables change nahi hote.
• Dynamic Scope: locals() ka output depend karta hai ki usko kaha call kiya gaya hai.

Common Syntax Variations


1. Specific Variable Access Karna
locals()['variable_name']

2. Variables ko Filter Karna Specific prefix wale variables ko extract karne ke liye:
{k: v for k, v in locals().items() if k.startswith('my_')}

3. Values Dynamically Update Karna (Avoid in Practice)


local_vars = locals()
local_vars['new_var'] = 100
print(local_vars) # {'new_var': 100}

Best Practices
• locals() ka use sirf introspection aur debugging ke liye karein, variables modify karne ke liye
nahi.
• Agar function ya complex scope me use kar rahe hain, to dhyan dein ki sensitive data expose na
ho.

=============================== ===============================

8
Important Note: Django View Functions me URL
Parameters Pass Karna

Django View Functions me URL Parameters Kaise Pass Kare


Django me jab aap URL pattern me koi parameter define karte hain (jaise int:task index), to usko
aapko apni view function me as an argument lena zaroori hota hai. Isse aap URL se milne wale value
ko view function ke logic me use kar sakte hain.

URL Patterns Aur View Function Parameters


Django ka URL dispatcher URL pattern me diye gaye parameters ko extract karke unko corresponding
view function ko pass karta hai. Niche ek example diya gaya hai jo is concept ko samjhne me madad
karega.
Example 1: Basic URL Parameter Handling
Maan lijiye aapke paas ye URL pattern hai:
path(’<int:task_index>/’, DeveloperTaskView.as_view()), # GET, PUT, DELETE ke liye task_index

Yaha URL ek integer parameter task index expect karta hai. Django is value ko URL se extract karke
DeveloperTaskView class ke method ko as an argument bhejega.

Yeh Kaise Kaam Karta Hai?


1. URL Pattern: path(’<int:task index>/’, DeveloperTaskView.as view())
• Ye pattern task index ko URL se capture karega.
• Agar URL /api/tasks/0/ hai, to task index = 0 hoga.
2. View Function: View function ya method (get, put, patch etc.) ko ye parameter lena hoga.

Example View Function


Aap apni view class me task index parameter capture kar sakte hain:

class DeveloperTaskView(APIView):
def patch(self, request, task_index):
# Yaha task_index URL se automatically pass hoke aayega
print(f"Updating task at index {task_index} for user_id {request.user_id}")

# Yaha aapka update logic hoga

Kyun Ye Kaam Karta Hai?


• URL Parameter Capture: int:task index URL se ek integer capture karta hai aur use
task index parameter ke roop me bhejta hai.

• View Function Parameter: View function ya method me jo argument diya gaya hai (task index),
wahi URL se milta hai.

9
Example 2: Multiple Parameters in URL
Agar aapko ek se zyada parameters pass karne hain, to aap aisa likh sakte hain:

path(’<int:user_id>/<int:task_index>/’, DeveloperTaskView.as_view()), # user_id aur task_index pass

Agar URL /api/tasks/6/2/ hai, to:

• user id = 6
• task index = 2

Updated View Function


class DeveloperTaskView(APIView):
def patch(self, request, user_id, task_index):
# Yaha user_id aur task_index URL se pass ho kar aayenge
print(f"Updating task {task_index} for user {user_id}")

# Yaha aapka update logic hoga

Key Points Yaad Rakhein


1. URL Parameters: Jo bhi aap path() me define karenge (<int:task index>), woh URL se
extract kiya jayega.

2. View Function Arguments: Jo parameters URL pattern me diye gaye hain (task index,
user id, etc.), unko aapko view function me as an argument lena hoga.
3. Correct Matching: Aapka URL pattern aur view function ka parameter name aur type match
karna chahiye.

Ye concept Django ke URL routing ka ek important hissa hai jo har developer ko samajhna chahiye.
=============================== ===============================
article xcolor

Tracing and Modifying ROOT URLCONF in Django


ROOT URLCONF ek setting hai jo settings.py file me define hoti hai aur yeh batati hai ki sabse pehle
Django kis urls.py file ko check karega jab koi request aaye.
1. ROOT URLCONF Kya Hai?
Jab bhi koi HTTP request Django application ke server pe aati hai, toh ROOT URLCONF us request ko
process karne ke liye batata hai ki kaunsa URL configuration file use hoga.
Example:
ROOT_URLCONF = "my_project.urls"
Yeh line specify karti hai ki jab koi bhi request aaye, toh sabse pehle my project folder ke andar jo
urls.py file hai, usko check kiya jayega.
2. Multi-App Projects ke liye Customization
Agar project me multiple apps hain, toh ROOT URLCONF me define urls.py file se har app ka urls.py
include kiya jata hai:

from django.urls import include, path

urlpatterns = [
path("app1/", include("app1.urls")), # App1 ke URLs ko handle karega
path("app2/", include("app2.urls")), # App2 ke URLs ko handle karega
]

10
3. Dynamic Modification
Kuch advanced use cases jaise ki multi-tenancy me runtime par ROOT URLCONF ko dynamically modify
kiya ja sakta hai:
from django.conf import settings
settings.ROOT_URLCONF = "another_project.urls"

Iska matlab hai ki request ko ek naye URL configuration file ki taraf redirect kiya ja sakta hai, jaise ki
alag-alag tenants ke liye alag URL configurations.
4. Debugging ke Liye ROOT URLCONF Ka Mahatva
• settings.py file me ROOT URLCONF ko check karein taki pata chale ki request kis urls.py file ko
refer kar rahi hai.
• urlpatterns ko follow karein taki pata chale ki kis URL par kaunsa view function call ho raha
hai.
• Agar request expected response nahi de rahi, toh ROOT URLCONF check karna ek acha debugging
step ho sakta hai.

Summary: ROOT URLCONF Django application ka primary URL configuration define karta hai. Yeh
batata hai ki sabse pehle kaunsi urls.py file ko use kiya jayega, aur usme se kaunsi routes available
hain. Multi-app projects me har app ke urls.py ko include kiya jata hai, aur kuch advanced cases me
isko dynamically modify bhi kiya ja sakta hai.
=============================== ===============================
Importing a cURL Request into Postman: Capturing Network Requests, Copying cURL,
and Automatically Setting Up Request in Postman

Importing a cURL Request into Postman: Capturing and Con-


verting Network Requests to Postman
Yeh process ”Importing a cURL request into Postman” kehlata hai. Iska matlab hai ke agar tumne kisi
browser ke developer tools se ek HTTP request capture ki hai, toh usse Postman me import karke test
ya debug kar sakte ho. Chalo step-by-step samajhte hain:

Steps for Importing a cURL Request into Postman: From Browser


Developer Tools to Postman Request
1. Browser Developer Tools Open Karo: Request Capture Karna
• Apna browser (Chrome, Firefox, etc.) open karo.
• Jis webpage ka network request capture karna hai, waha jao.
• Right-click karo aur Inspect select karo ya Ctrl + Shift + I (Windows/Linux) ya Cmd +
Option + I (Mac) dabao.

2. Network Tab Par Jao: Network Activity Dekhna


• Developer Tools me Network tab par click karo.
3. Request Trigger Karo: Request Capture Karna

• Page refresh karo ya koi aisa action lo jo request bhejta ho (e.g., button click karna, form
submit karna).
4. Request Dhundo: Network Tab Me Apni Request Dekho
• Network tab me jo requests show ho rahi hain, unme se apni request dhundo.
• Request type (e.g., XHR, Fetch) ya naam ke basis par filter kar sakte ho.
5. Request Copy Karo: cURL Format Me Copy Karna
• Apni request par right-click karo.

11
• Context menu se Copy → Copy as cURL (bash) select karo.
6. Postman Open Karo: Request Import Karne Ke Liye
• Postman open karo ya Postman web app launch karo.

7. cURL Import Karo: Postman Me Request Convert Karna


• Postman me Import button par click karo.
• Raw Text option select karo.
• Clipboard se copied cURL command paste karo aur Continue dabao.

8. Request Edit Karo Aur Send Karo


• Postman automatically cURL command ko request me convert kar dega.
• Tum headers, body ya parameters ko modify kar sakte ho.
• Send button dabao aur response dekho.

Behind the Scenes: cURL Aur Postman Ka Kaam Kaise Hota


Hai
• cURL (Client URL) ek command-line tool hai jo HTTP requests send karne ke liye use hota hai.
Jab tum ”Copy as cURL” karte ho, toh poori request (headers, body, method, etc.) ek format me
milti hai jo Postman samajh sakta hai.
• Postman ek API testing tool hai jo cURL request ko ek graphical interface request me convert
karta hai, taaki tum bina manually details enter kiye request send kar sako.

Yeh process debugging aur testing ke liye bahut useful hoti hai, taaki tum browser me chali requests ko
Postman me easily test kar sako.
=============================== ===============================
Difference Between PUT and PATCH in Short and Simple Terms

Difference Between PUT and PATCH: Key Distinctions in HTTP


Methods
Jab bhi kisi resource ko HTTP ke through update karna hota hai, toh PUT aur PATCH dono use kiye
ja sakte hain. Lekin yeh dono tarike alag tareeke se kaam karte hain.

PUT: Complete Update of the Resource


Definition: PUT method ek resource ko completely replace kar deta hai. Matlab agar tumne sirf kuch
fields provide ki hain, toh jo baaki fields hain wo delete ya default ho sakti hain.
Key Characteristics:
• Pura resource replace hota hai jo naye data se provide kiya gaya hai.

• Agar koi field request me include nahi ki gayi, toh wo hata di jati hai ya default ho jati hai.
Example:
PUT /user/123
{
"name": "John Doe",
"email": "[email protected]"
}
Agar pehle ke resource me ”address” field bhi thi, lekin request me nahi di gayi, toh wo field remove ho
jayegi.

12
PATCH: Partial Update of the Resource
Definition: PATCH method sirf wahi fields modify karta hai jo request me di gayi hain. Baaki fields
same rehti hain.
Key Characteristics:
• Efficient hai agar sirf kuch fields update karni ho.
• Sirf wahi fields modify hoti hain jo request me include ki gayi hain.
Example:
PATCH /user/123
{
"email": "[email protected]"
}
Is case me sirf ”email” field update hogi, aur ”name” ya ”address” jaise fields same rahenge.

Summary: PUT vs PATCH


• PUT: Pura resource replace karta hai naye data se.
• PATCH: Sirf specific fields ko update karta hai bina baaki resource ko modify kiye.
=============================== ===============================
Django Mein Celery, Redis, Celery Beat, aur Caching Ka Com-
plete Guide
Is guide mein hum Django project mein Celery, Redis, Celery Beat, aur Caching ko integrate karne
ke steps dekhenge. Har step ko detail mein samjhaya jayega, filenames, code, aur comments ke saath.
Ye Components Kya Hain?
• Celery: Asynchronous tasks ke liye use hota hai. Isse aap background mein tasks run kar sakte
hain, jaise emails bhejna, data processing karna, etc.
• Redis: Celery ka message broker hai. Ye tasks ko hold karta hai aur unhe queue mein rakhta hai
taki Celery workers unhe process kar sake.
• Celery Beat: Periodic tasks ke liye ek scheduler hai. Isse aap specific intervals par tasks schedule
kar sakte hain (e.g., har ghante, har din).
• Caching: Django app ko fast banata hai by frequently accessed data ko memory mein store karke.
Step-by-Step Setup
1. Required Packages Install Kare
Sabse pehle Celery, Redis, aur Django-Celery-Beat package ko install kare:
pip install celery[redis] django-celery-beat redis

2. Django Mein Celery Set Up Kare


Directory Structure:
Aapke project folder ka structure kuch aisa hona chahiye:
myproject/
myproject/
__init__.py
settings.py
urls.py
wsgi.py
celery.py # <-- Naya file
myapp/
__init__.py
tasks.py # <-- Naya file
manage.py

13
2.1 celery.py File Banaye
Apne project directory mein (jahan settings.py hai), ek celery.py file banaye. Ye file Celery ko
configure karega taki wo aapke Django project ke saath kaam kare.
# myproject/celery.py

from __future__ import absolute_import, unicode_literals


import os
from celery import Celery

# Django settings module ko set kare


os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

# Celery instance banaye aur project ke naam se naamkaran kare


app = Celery('myproject')

# Django ke settings se Celery ko configure kare


app.config_from_object('django.conf:settings', namespace='CELERY')

# Sabhi registered Django apps mein tasks ko automatically discover kare


app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
# Celery kaam kar raha hai ya nahi, ye debug task se check kare
print('Request:␣{0!r}'.format(self.request))

Explanation:
• os.environ.setdefault(’DJANGO SETTINGS MODULE’, ’myproject.settings’): Default Django
settings module set karta hai.
• app = Celery(’myproject’): Celery app ko initialize karta hai aur uska naam myproject rakhta
hai.
• app.config from object(’django.conf:settings’, namespace=’CELERY’): Celery configura-
tion ko Django ke settings.py se load karta hai.
• app.autodiscover tasks(): Sabhi installed Django apps mein tasks ko automatically dhoondhta
hai.
2.2 init .py File Update Kare
Ensure kare ki Celery Django app start hote hi load ho jaye. myproject/ init .py file ko open kare
aur ye add kare:
# myproject/__init__.py

from __future__ import absolute_import, unicode_literals

# Ye ensure karega ki app hamesha import ho jab


# Django start hota hai taki shared_task is app ka use kare.
from .celery import app as celery_app

__all__ = ('celery_app',)

3. settings.py Mein Celery Configure Kare


settings.py mein Redis broker URL ko configure kare:
# myproject/settings.py

# Celery configuration
CELERY_BROKER_URL = 'redis://localhost:6379/0' # Redis server URL
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' # Results store karne ke liye Redis

14
CELERY_ACCEPT_CONTENT = ['json'] # Task messages ke liye sirf JSON accept kare
CELERY_TASK_SERIALIZER = 'json' # Task messages JSON format mein serialize kare
CELERY_TIMEZONE = 'UTC' # Task scheduling ke liye timezone set kare

Explanation:
• CELERY BROKER URL: Redis ko broker ke roop mein specify karta hai.

• CELERY RESULT BACKEND: Task results store karne ke liye Redis use karta hai.
• CELERY ACCEPT CONTENT aur CELERY TASK SERIALIZER: Tasks ko JSON format mein serialize karta
hai.
• CELERY TIMEZONE: Task scheduling ke liye timezone set karta hai.

4. Celery Tasks Banaye aur Configure Kare


Background tasks banaye jo Celery execute kar sake. Apne app mein tasks.py file banaye.
4.1 tasks.py File Banaye

# myapp/tasks.py
from celery import shared_task

# Example task: Do numbers ko asynchronously add kare


@shared_task
def add(x, y):
return x + y

# Ek aur task: Email bhejne ka simulate kare


@shared_task
def send_email_task(email):
# Email bhejne ka simulate kare
print(f"Sending␣email␣to␣{email}")

Explanation:
• @shared task: Ye decorator ek function ko Celery task ke roop mein register karta hai, jise asyn-
chronously execute kiya ja sakta hai.
• add(): Do numbers ko asynchronously add karta hai.

• send email task(): Email bhejne ka simulate karta hai.


4.2 Tasks Ko Asynchronously Call Kare
Apne code mein kahi se bhi tasks ko call kare:
# Task ko asynchronously call kare
from myapp.tasks import add
result = add.delay(4, 6)

Explanation:

• add.delay(4, 6): Task ko Celery ko bhejta hai taki wo background mein process ho sake.
5. Periodic Tasks Ke Liye Celery Beat Set Up Kare
Celery Beat periodic tasks ko schedule karta hai.
5.1 django-celery-beat Install Kare
Required package ko install kare:
pip install django-celery-beat

15
5.2 INSTALLED APPS Mein Add Kare
settings.py mein ’django celery beat’ ko INSTALLED APPS mein add kare:
# myproject/settings.py

INSTALLED_APPS = [
...
'django_celery_beat', # Ye line add kare
]

5.3 Database Migrate Kare


Celery Beat ke liye required tables banane ke liye migrations run kare:
python manage.py migrate django_celery_beat

5.4 Periodic Tasks Schedule Kare


Periodic tasks ko celery.py mein configure kare:
# myproject/celery.py
from celery.schedules import crontab

app.conf.beat_schedule = {
'send-email-every-minute': {
'task': 'myapp.tasks.send_email_task',
'schedule': crontab(minute='*/1'), # Har minute run kare
'args': ('[email protected]',),
},
}

Explanation:
• crontab(minute=’*/1’): Task ko har minute run karne ke liye define karta hai.
• args: Task function ko pass kiye gaye arguments.

5.5 Celery Beat Run Kare


Tasks ko schedule karne ke liye, Celery Beat ko niche diye gaye command se run kare:
[language=bash]
celery -A myproject beat --loglevel=info

6. Redis Ke Saath Caching Set Up Kare


6.1 django-redis Install Kare
Required Redis package ko install kare:
pip install django-redis

6.2 settings.py Mein Caching Configure Kare


settings.py mein cache backend ko Redis ke saath configure kare:
# myproject/settings.py

CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1', # Redis database 1
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
},
}
}

16
Explanation:
• ’BACKEND’: Cache backend specify karta hai (yahan Redis hai).
• ’LOCATION’: Redis server aur database (caching ke liye database 1).

6.3 Views Mein Caching Ka Use Kare


Aap views ya data ko cache kar sakte hain.
# myapp/views.py
from django.shortcuts import render
from django.core.cache import cache

def my_view(request):
# Cache se data fetch kare
data = cache.get('my_key')

if not data:
# Agar cache mein nahi hai, to database se fetch kare ya compute kare
data = 'Expensive␣data'
# Data ko cache mein 1 hour (3600 seconds) ke liye store kare
cache.set('my_key', data, timeout=3600)

return render(request, 'my_template.html', {'data': data})

Explanation:
• cache.get(’my key’): Cache se data fetch karta hai.

• cache.set(’my key’, data, timeout=3600): Data ko 1 hour (3600 seconds) ke liye cache mein
store karta hai.

7. Sab Kuch Run Kare


Apne project ko run karne ke liye, in steps ko follow kare:

• Redis Start Kare (agar already running nahi hai):


redis-server

• Django Development Server Run Kare:


python manage.py runserver

• Celery Worker Start Kare (naye terminal window mein):


celery -A myproject worker --loglevel=info

• Celery Beat Start Kare (periodic tasks schedule karne ke liye):


celery -A myproject beat --loglevel=info

Summary
• Celery: Background tasks ko asynchronously run karne ke liye use hota hai.
• Redis: Celery ka message broker aur cache backend ke roop mein use hota hai.
• Celery Beat: Periodic tasks ko schedule karne ke liye use hota hai.

• Caching: Performance improve karne ke liye data ko temporarily memory mein store karta hai.
=============================== ===============================

17
Python Virtual Environment: Summary
A virtual environment in Python ek isolated environment hota hai jo ek project ke liye specific
dependencies manage karne ki suvidha deta hai bina system-wide Python installation ko affect kiye. Isse
alag-alag projects ke dependencies conflict nahi karte hain.
Why Use Virtual Environments?
• Isolation: Har project ka apna alag environment hota hai.
• Version Management: Alag-alag projects ke liye alag package versions use kiye ja sakte hain.
• Cleaner Environment: System Python ko cluttered hone se bachata hai.

Commands and Examples


1. Create a Virtual Environment

python -m venv env_name

Explanation: env name virtual environment ka folder name hota hai (e.g., env).
Example:
python -m venv myenv

2. Activate the Virtual Environment


Windows:
.\env_name\Scripts\activate

Linux/Mac:
source env_name/bin/activate

Example:
source myenv/bin/activate

Activate hone ke baad terminal prompt me environment ka naam show karega, jaise (myenv).
3. Deactivate the Virtual Environment

deactivate

Example:
(myenv) deactivate

Ye command global Python environment me wapas le aayegi.


4. Install Packages Inside the Virtual Environment
Activate hone ke baad pip ka use karke packages install kar sakte hain:
pip install package_name

Example:
pip install django

5. Save Installed Packages


Environment ke dependencies ko requirements.txt me save karne ke liye:
pip freeze > requirements.txt

18
6. Install Packages from requirements.txt

pip install -r requirements.txt

7. Delete a Virtual Environment


Virtual environment delete karne ke liye uska folder remove karein:
rm -rf env_name

Example Workflow
1. Ek project folder banayein aur usme navigate karein:
mkdir my_project
cd my_project

2. Virtual environment create karein:


python -m venv env

3. Environment activate karein:


source env/bin/activate

4. Dependencies install karein:


pip install django

5. Installed packages save karein:


pip freeze > requirements.txt

6. Kaam khatam hone ke baad deactivate karein:


deactivate

Key Points
• Har project ka apna isolated environment hota hai.
• Project-specific commands run karne se pehle virtual environment activate karein.
• pip freeze ka use karke environment setup share karein.

Understanding ‘pip freeze‘ in Django (or Python in General)


The pip freeze command is used to list all installed Python packages in your currently active virtual
environment along with their exact versions. This is particularly useful in Django projects to generate a
requirements.txt file, which helps in sharing and replicating the project setup across different systems.
Example Usage and Explanation
1. List Installed Packages
To view all installed packages and their versions in the current environment, use:
pip freeze

Explanation: This command fetches and displays the list of all installed dependencies in the active
virtual environment.
Example Output:
Django==4.2.5
djangorestframework==3.14.0
mysqlclient==2.1.3

19
2. Save Installed Packages to requirements.txt
To store the installed packages in a requirements.txt file, run:
pip freeze > requirements.txt

Explanation: This command creates a text file named requirements.txt and writes all installed
package names along with their versions into it. This file is useful for setting up the same environment
on another system.
3. Install Packages from requirements.txt
If you need to install the exact dependencies listed in requirements.txt, use:
pip install -r requirements.txt

Explanation: This command reads the requirements.txt file and installs all the listed packages with
the specified versions, ensuring that your environment matches the one where the file was created.

20
Comprehensive Guide to Django ORM: CRUD Operations aur Query Optimization

1. Create (Naya Record Insert Karna)


Using .create()
User.objects.create(username='JohnDoe', email='[email protected]', password='
securepassword')

- User: Yeh model database table User ko represent karta hai. - objects.create(): Ek hi step me
naya record create aur save karta hai. - username, email, password: Ye fields naye record ko populate
karne ke liye hain.
Using Model Instance
user = User(username='JaneDoe', email='[email protected]')
user.set_password('securepassword') # Password ko hash karne ke liye
user.save()

- User(username=..., email=...): Ye ek unsaved object create karta hai. - setp assword() : P asswordkosecurelyhashk
save() : Objectkodatabasemesavekartahai.

2. Read (Records Retrieve Karna)


Retrieve Sabhi Records
users = User.objects.all()

- all(): User table ke sabhi records ko QuerySet ke roop me fetch karta hai.
Retrieve Ek Specific Record
user = User.objects.get(id=1)

- get(): Sirf ek record fetch karega jisme id=1 hoga. - Agar record nahi mila toh DoesNotExist
error aayega, aur agar multiple matches hue toh MultipleObjectsReturned error milega.
Retrieve with Filtering
active_users = User.objects.filter(is_active=True)

- filter(): Sirf wahi records fetch karega jo condition isa ctive = T ruematchkartehain.
Retrieve Specific Fields
user_emails = User.objects.values('email')

- values(’field’): Sirf specified field ke data ka dictionary return karega.

3. Update (Records Modify Karna)


Update Ek Single Record
user = User.objects.get(username='JohnDoe')
user.email = '[email protected]'
user.save()

- get(): Jo record update karna hai usko fetch karta hai. - save(): Database me changes
save karta hai.
Update Multiple Records
User.objects.filter(is_active=False).update(is_active=True)

- filter(): Multiple records ko select karega. - update(): Selected records ko bulk me


update karega.

21
4. Delete (Records Remove Karna)
Delete Ek Single Record
user = User.objects.get(username='JohnDoe')
user.delete()

- delete(): Record database se hata dega.


Delete Multiple Records
User.objects.filter(is_active=False).delete()

- filter(): Jo records delete karne hain unko select karega. - delete(): Sab selected
records delete kar dega.

5. Common Aggregation aur Annotation


Count
user_count = User.objects.count()

- count(): QuerySet me kitne records hain uska count return karega.


Aggregate
stats = User.objects.aggregate(avg_id=Avg('id'))

- aggregate(): Fields par calculations karta hai jaise Avg, Max, Sum.
Annotate
users_with_groups = User.objects.annotate(group_count=Count('groups'))

- annotate(): Har record ke saath ek calculated field groupc ountaddkarega.


6. Bulk Operations
Bulk Create
users = [User(username='User1'), User(username='User2')]
User.objects.bulk_create(users)

- bulk create(): Ek saath multiple records insert karne ke liye use hota hai. Yeh ek hi
query me execute hota hai, jo performance improve karta hai.
Bulk Update
users = User.objects.filter(is_staff=False)
for user in users:
user.is_active = True
User.objects.bulk_update(users, ['is_active'])

- bulk update(): Ek saath multiple records update karne ke liye use hota hai. Isme sirf
wahi fields update hoti hain jo specify ki hoti hain (yaha is active).

7. QuerySet Chaining
users = User.objects.filter(is_staff=True).exclude(is_active=False).order_by('-
date_joined')

- filter(): Jo records condition ko match karte hain, unhe fetch karta hai. - exclude():
Jo condition ko match karte hain, unko hata kar baaki records fetch karta hai. - order by():
Sorting ke liye use hota hai (-date joined descending order ke liye hai).

22
8. Raw SQL Queries
users = User.objects.raw('SELECT␣*␣FROM␣auth_user␣WHERE␣is_active=%s', [True])

- raw(): Jab ORM se zyada control chahiye ho, tab SQL queries likh ke execute karne ke
liye use hota hai.

9. Transactions
from django.db import transaction

with transaction.atomic():
user1 = User.objects.create(username='Temp1')

- transaction.atomic(): Yeh ensure karta hai ki agar ek operation fail ho jaye, to saari
operations rollback ho jayein, jisse data consistency bani rahe.

10. Performance Optimization


Select Related
users = User.objects.select_related('profile').all()

- select related(): Jab ForeignKey relations efficiently load karne ho tab use hota hai,
yeh ek hi query me data fetch karta hai.
Prefetch Related
users = User.objects.prefetch_related('groups').all()

- prefetch related(): Jab many-to-many ya reverse relationships ko efficiently fetch karna


ho, tab use hota hai. Yeh alag query execute karke memory me optimize karta hai.
Django Relationships: ForeignKey aur One-to-One
Django mein, models ke beech relationships ko define karne ke liye fields jaise ForeignKey,
OneToOneField, aur ManyToManyField ka use kiya jata hai. Ye fields tables ko link karne
aur database management ko simplify karne mein madad karte hain. Aaj hum ForeignKey (Many-to-One)
aur One-to-One relationships par focus karenge aur dekhenge ki ye Django mein kaise kaam
karte hain.

1. ForeignKey (Many-to-One Relationship)


ForeignKey ka use Many-to-One relationship define karne ke liye kiya jata hai. Is relationship
mein, ek related model ka record current model ke multiple records ke saath associated ho
sakta hai.
ForeignKey Ka Syntax
class Book(models.Model):
title = models.CharField(max_length=100) % Book ka title
author = models.ForeignKey( % Author se ForeignKey relationship
'Author', % Related model
on_delete=models.CASCADE, % Jab referenced object delete ho, to kya hoga
)

• ForeignKey: Book aur Author ke beech many-to-one relationship banata hai.


• ’Author’: Ye related model hai jisse ye field link karta hai.

• on delete=models.CASCADE: Agar ek Author delete ho jata hai, to usse related sabhi


Book records bhi delete ho jayenge.
• author: Ye field Book mein hai jo Author se link karta hai.

23
ForeignKey Ka Example
class Author(models.Model):
name = models.CharField(max_length=100) % Author ka naam

def __str__(self):
return self.name

class Book(models.Model):
title = models.CharField(max_length=100) % Book ka title
author = models.ForeignKey( % Author se ForeignKey relationship
'Author', % Related model 'Author'
on_delete=models.CASCADE, % Author delete hone par related Book bhi
delete ho jayegi
)

def __str__(self):
return self.title

Database Structure
• Author Table:
id name
1 J.K.Rowling
2 GeorgeR.R.M artin

• Book Table:
id title author id(F oreignKey)
1 HarryP otter1 1
2 HarryP otter2 1
3 Gameof T hrones 2

• ForeignKey Kaise Kaam Karta Hai:


– Har Book record ek Author se author field ke through link hota hai.
– Ek hi Author ke multiple Book records ho sakte hain, lekin har Book ka sirf ek
hi Author hoga.

Data Access Kaise Kare


Agar aap ek book ka author access karna chahte hain, to aap is tarah kar sakte hain:

book = Book.objects.first()
print(book.author.name) % Book ke author ka naam print karega

2. One-to-One Relationship
Ek One-to-One relationship ka matlab hai ki ek model ka ek record dusre model ke ek record
ke saath associated hota hai. Ye tab useful hota hai jab aap kisi model ko additional fields
ya attributes ke saath extend karna chahte hain, bina original model ko modify kiye.
One-to-One Relationship Ka Syntax
class Employee(models.Model):
name = models.CharField(max_length=100) % Employee ka naam

class EmployeeDetails(models.Model):
employee = models.OneToOneField( % One-to-One relationship
'Employee', % Related model
on_delete=models.CASCADE, % Jab related Employee delete ho, to kya hoga
)

24
phone = models.CharField(max_length=15) % Employee ka phone number
address = models.TextField() % Employee ka address

• OneToOneField: EmployeeDetails aur Employee ke beech one-to-one relationship banata


hai.
• ’Employee’: Ye model hai jisse ye field related hai (target model).

• on delete=models.CASCADE: Agar ek Employee delete ho jata hai, to uska associated EmployeeDetail


bhi delete ho jayega.
• employee: Ye field EmployeeDetails mein hai jo Employee se link karta hai.

One-to-One Relationship Ka Example


class Employee(models.Model):
name = models.CharField(max_length=100) % Employee ka naam

def __str__(self):
return self.name

class EmployeeDetails(models.Model):
employee = models.OneToOneField( % Employee se One-to-One relationship
'Employee', % Related model
on_delete=models.CASCADE, % Employee delete hone par related
EmployeeDetails bhi delete ho jayega
)
phone = models.CharField(max_length=15) % Employee ka phone number
address = models.TextField() % Employee ka address

def __str__(self):
return f"{self.employee.name}'s Details"

Database Structure
• Employee Table:
id name
1 JohnDoe
2 JaneSmith

• EmployeeDetails Table (foreign key column employee id hai):

id employee id(F oreignKey) phone address


1 1 123 − 456 − 7890 1234ElmSt
2 2 987 − 654 − 3210 5678OakAve

One-to-One Mein Foreign Key Column Ka Naam


By default, related table (EmployeeDetails) mein foreign key column ka naam
<related model name> id hota hai. Is case mein, ye employee id hoga.
Foreign Key Column Ka Naam Customize Kare
Agar aap foreign key column ka naam customize karna chahte hain, to db column option ka
use kar sakte hain:

class EmployeeDetails(models.Model):
employee = models.OneToOneField(
'Employee',
on_delete=models.CASCADE,
db_column='emp_id' % Foreign key column ka custom naam

25
)
phone = models.CharField(max_length=15)
address = models.TextField()

=============================== ===============================
Using Q() in Django Queries
Step-by-Step Example with Models and Queries
Why Use Q() in Django Queries?
Jab hume complex queries likhni hoti hain, jaise:
• Multiple conditions ko **AND** ya **OR** ke saath combine karna.
• Related models (ForeignKey wale fields) pe filtering karni.

• **Dynamic filtering** jisme kabhi condition change ho sakti hai.


Tab Q() ka use karna best hota hai.
Agar hum Q() ka use nahi karenge, toh **chained filter()** method likhna padega, jo har
baar **AND condition** hi lagayega, aur | (OR) ka use nahi kar paayenge.
Problem Without Q():
# Yeh sirf AND condition ko support karega
tasks = Task.objects.filter(user username='JohnDoe').filter(status='completed')

Yahan AND to work karega, lekin agar hume **OR** ya complex conditions likhni ho toh
problem ho sakti hai. Isi wajah se hume Q() ka use karna padta hai.
Models
Hum do models use karenge: User aur Task. User mein username hoga, aur Task ka ek ForeignKey
relation hoga User ke saath.
from django.db import models

class User(models.Model):
username = models.CharField(max_length=100)
email = models.EmailField()

def str (self):


return self.username

class Task(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
status = models.CharField(max_length=20)

def str (self):


return self.title

Step 1: Using Q() for Complex Queries


Ab hum Q() object use karke Task objects ko filter karenge.
Example 1: Basic Query with Q()
Hum aise tasks filter karna chahte hain jisme:
• User ka username ’JohnDoe’ ho.
• Task ka status ’completed’ ho.

26
from django.db.models import Q
from .models import Task

tasks = Task.objects.filter(
Q(user username='JohnDoe') & Q(status='completed')
)

Explanation:
• Q(user username=’JohnDoe’) - Task ko filter karta hai jisme User ka username ’JohnDoe’
ho.

• Q(status=’completed’) - Sirf wahi tasks lega jisme status ’completed’ ho.


• & (AND) - Dono conditions true honi chahiye tabhi record milega.
Example 2: Using Q() with OR Condition
Agar hum chahte hain ki tasks tabhi aaye jab:
• username ’JohnDoe’ ho ya phir status ’completed’ ho.

tasks = Task.objects.filter(
Q(user username='JohnDoe') | Q(status='completed')
)

Without Q(), yeh possible nahi hota!


Explanation:

• | (OR) - Koi bhi ek condition true ho toh record return hoga.


Example 3: Filtering with in for Multiple Values
Agar hume multiple usernames aur multiple statuses ke basis pe filter karna ho?
usernames = ['JohnDoe', 'JaneSmith']
statuses = ['completed', 'pending']

tasks = Task.objects.filter(
Q(user username in=usernames) & Q(status in=statuses)
)

Explanation:

• user username in=usernames - User ka username JohnDoe ya JaneSmith ho sakta hai.


• status in=statuses - Task ka status completed ya pending ho sakta hai.
Example 4: Checking for Null Values in Related Models
Agar hume aise tasks chahiye jisme User ke paas email na ho (i.e., NULL ho):
tasks = Task.objects.filter(
Q(user email isnull=True)
)

Without Q(), yeh query likhna complex ho sakta hai!


Conclusion
Q() object Django me queries ko flexible aur powerful banata hai. Agar aapko complex filtering
karni hai toh Q() ka use karna best practice hai! Agar hum Q() ka use nahi karenge toh:
• **AND conditions** hi use ho payengi.
• **OR conditions** likhna mushkil ho jayega.
• **Dynamic conditions** implement karna hard ho jayega.

27
Toh agar aapko advanced queries likhni hain, toh **Q() ka use zaroor karein!**
article xcolor listings
Bilkul, main aapko ek alag aur simple example ke saath samjhata hoon. Is baar tables
ka context thoda badalte hain.
queries.append(Q(order products name in=product_list))

Scenario:
Maan lo, humare paas 2 tables hain:
• Order Table:
– order id (Primary Key)
– order name
– products (Ye ek Many-to-Many relationship hai jo Product Table se link hota hai)
• Product Table:
– product id (Primary Key)
– name (Product ka naam)

Example:
Product Table:
product id name
1 P roductX
2 P roductY
3 P roductZ

Order Table:
order id order name products
1 Order1 [P roductX, P roductY ]
2 Order2 [P roductX]
3 Order3 [P roductZ]

‘product list‘ List:


product_list = ['Product X']

Ab samajhte hain ki ye line kya karti hai:


queries.append(Q(order products name in=product_list))

Step-by-Step Explanation:
• ‘Q(order products name in=productl ist)‘ :

• ‘order‘: Ye ‘Order‘ model ko refer karta hai.


• ‘products‘: Ye ‘Order‘ model ki field hai jo Many-to-Many relationship ko represent
karti hai. Matlab har
order ke multiple products ho sakte hain.
• ‘name‘: Ye ‘Product‘ table ke ‘name‘ field ko refer karta hai, jo product ka
naam store karta hai.
• ‘in=productl ist‘ : ‘productl ist‘eklisthaijismehumcheckkarrahehainki‘P roduct‘tableke‘name‘f ieldkakoibhinaamislist

28
Example ko samajhte hain:
• Order 1:
– Products: ‘Product X‘, ‘Product Y‘
– Condition: Hum dekh rahe hain ki ‘Product X‘ is ‘productl ist‘meinhaiyanahi.Result :
Order 1matchkaregaaurquerymeinaayega.

–• Order 2:
– Products: ‘Product X‘
– Condition: Hum dekh rahe hain ki ‘Product X‘ is ‘productl ist‘meinhaiyanahi.Result :
Order 2matchkaregaaurquerymeinaayega.

–• Order 3:
– Products: ‘Product Z‘
– Condition: Hum dekh rahe hain ki ‘Product X‘ is ‘productl ist‘meinhaiyanahi.Result :
Order 3match nahi karega, kyunki‘P roductZ‘islistmeinnahihai.

Final Filtered Result:


Is query ke through sirf wo orders filter honge jisme products ka naam ‘Product X‘ list
mein ho. Yani, Order 1 aur Order 2 match karenge, aur Order 3 match nahi karega.

SQL Query (for illustration):


SELECT * FROM order
WHERE products.name IN ('Product X')

Kyun use karein Q()?


Agar hum Q() ka use nahi karenge aur directly filter() ka use karenge toh problem ho sakti
hai:
queries.append(filter(order products name in=product_list))

Ye sirf ek simple condition ko handle karega, lekin agar hume:


–• Multiple conditions combine karni ho (AND / OR)

• Dynamic queries likhni ho jisme kabhi condition change ho sakti hai


• Complex lookups perform karni ho
Toh Q() ka use karna best hota hai.

Conclusion:
Aapka ‘queries.append(Q(order products name in=productl ist))‘kamatlabhai :
"Hum un orders ko filter karna chahte hain jinke associated products ka naam ‘Product
X‘ list mein hai."
Is query ko run karne par Order 1 aur Order 2 milenge, jo Product X ko apne products
mein rakhte hain.
Yeh example aapko zyada clear ho gaya hoga!
=============================== ===============================

29
Table Naming in Django Models
1. Default Table Name:
Agar aap **koi custom table name specify nahi karte**, toh Django **automatically** ek table
name generate karega jo **app name aur model name** ka combination hoga. Yeh name **lowercase**
hoga aur words ko **underscore** se separate karega.
Format: appname modelname
Example: Maan lo ek Django app hai blog, jisme ek model hai BlogPost. Agar hum **koi
custom name specify nahi karte**, toh Django automatically table ka naam **blog blogpost**
bana dega.

class BlogPost(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()

Generated Table Name: blog blogpost


2. Custom Table Name:
Agar aap **apni pasand ka table name rakhna chahte hain**, toh aap Meta class ke andar **db table**
specify kar sakte hain:

class BlogPost(models.Model):
title = models.CharField(max_length=100)

class Meta:
db_table = 'custom_table_name'

Result: Django ab blog blogpost ke jagah **custom table name** use karega.
3. Plural Form in Admin:
Django by default model name ka **plural form** generate karta hai **admin panel** me.
Example: Agar aapka model BlogPost hai, toh Django isko **"BlogPosts"** likh ke dikhayega.
Agar aap **plural form ko customize** karna chahte hain, toh aap verbose name plural
ka use kar sakte hain:

class BlogPost(models.Model):
title = models.CharField(max_length=100)

class Meta:
verbose_name_plural = "Blog Entries"

Result: Django ab **"BlogPosts"** ke jagah **"Blog Entries"** show karega.


4. Primary Key:
Django **automatically** har table me ek **primary key** field add karta hai **id** naam
se, agar aap explicitly define nahi karte.
Example: Agar aap ye model likhte hain:

class BlogPost(models.Model):
title = models.CharField(max_length=100)

Toh Django automatically ye SQL create karega:

CREATE TABLE blog_blogpost (


id SERIAL PRIMARY KEY,
title VARCHAR(100)
);

Agar aap **custom primary key** rakhna chahte hain, toh manually define kar sakte hain:

class BlogPost(models.Model):
blog_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)

30
5. Migrations:
Django **models ko database tables me convert** karne ke liye **migrations** ka use karta
hai. Jab bhi aap **naya model banayein ya existing model me change karein**, toh aapko
migrations run karni padti hai.
Commands:

python manage.py makemigrations


python manage.py migrate

Explanation: - makemigrations: Ye **model changes ko detect** karke migration file


generate karta hai. - migrate: Ye migration file ko **database par apply** karta hai,
taaki tables update ho sakein.
6. Field Naming:
Django ke field names likhne ka **best practice**:
**Lowercase aur underscore** ka use karein (e.g., first name). **CamelCase na use
karein** (e.g., FirstName, firstName). **Python ke reserved keywords avoid karein** (e.g.,
class, def, for).
Example:

class Employee(models.Model):
first_name = models.CharField(max_length=50) # Correct
last_name = models.CharField(max_length=50) # Correct
age = models.IntegerField() # Correct
# class = models.CharField(max_length=50) # Wrong (Python keyword)

Example Model with Everything: Yahaan ek full example hai jisme **custom table name,
primary key, verbose name plural sab kuch define** kiya gaya hai:

from django.db import models

class BlogPost(models.Model):
blog_id = models.AutoField(primary_key=True) # Custom primary key
title = models.CharField(max_length=100)
content = models.TextField()
published_date = models.DateTimeField()

class Meta:
db_table = 'blog_posts' # Custom table name
verbose_name_plural = "Blog Posts" # Customize admin display

Final Result: - Table ka naam **blog posts** hoga. - **Primary key** blog id hogi (default
id nahi). - **Admin panel me "Blog Posts" dikhayega** (default "BlogPosts" nahi).
=============================== ===============================
Foreign Key Naming in Django
1. Default Foreign Key Field Name:
Agar aap ek **foreign key field define karte hain** Django model me, toh Django **automatically**
uska database column **is format me create karta hai**:
field name id
Yahaan: - field name: Model me jo foreign key field ka naam diya hai. - id: Django
automatically **"i d”suf f ix∗∗addkartahaitaakidatabasemeyehclearhokiyeh∗∗f oreignkeykaref erencehai∗
∗.
Example: Agar aap yeh models likhte hain:

from django.db import models

class Author(models.Model):
name = models.CharField(max_length=100)

class Book(models.Model):

31
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)

Toh Django **"book" table** me ek column create karega:


CREATE TABLE book (
id SERIAL PRIMARY KEY,
title VARCHAR(100),
author_id INTEGER REFERENCES author(id)
);

Table Name Columns


Generated Table: author id (primary key), name
book id (primary key), title, author id (foreign key)
Note: - author field ka actual **database column** **author id** hoga, na ki sirf **author**.
- Par Django **Python code me author field se access** karega, author id ka direct use nahi
hoga.
---
2. Custom Column Name:
Agar aap **foreign key ka database column name change** karna chahte hain, toh db column
use kar sakte hain:
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE, db_column='
writer_id')

Result: - **Default:** author id - **Custom:** writer id


SQL Table Structure After This Change:
CREATE TABLE book (
id SERIAL PRIMARY KEY,
title VARCHAR(100),
writer_id INTEGER REFERENCES author(id)
);

---
3. Foreign Key Relationships:
Django **automatically constraints add karta hai** taaki foreign key sirf valid records
ki taraf point kare.
Default behavior yeh hota hai ki foreign key **related model ke primary key** ko reference
karegi.
Example:
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)

CREATE TABLE book (


id SERIAL PRIMARY KEY,
title VARCHAR(100),
author_id INTEGER REFERENCES author(id) ON DELETE CASCADE
);

ON DELETE CASCADE: Agar **Author delete hota hai**, toh usse related **sabhi books bhi
delete ho jayengi**.
---
4. Field in Query:
Foreign key se related object ko query karne ke liye aap **field name hi use karte hain,
na ki column name**.
Example:

32
book = Book.objects.get(id=1)
print(book.author) # Returns Author object
print(book.author.name) # Prints author's name

Important: - **Django automatically related object fetch kar leta hai** (e.g., book.author
returns Author object). - **book.author id use karne ki zaroorat nahi hoti**, par agar
sirf **ID chahiye ho toh use kar sakte hain**:

print(book.author_id) # Prints only the author's ID

---
5. Best Practices:
**Consistent naming convention follow karein** (e.g., author instead of a id). **Use
descriptive names** (e.g., related author agar multiple relations ho). **ON DELETE behavior
samjhein** (e.g., CASCADE, SET NULL).
Example with All Best Practices:

class Author(models.Model):
name = models.CharField(max_length=100)

class Book(models.Model):
title = models.CharField(max_length=100)
writer = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True,
db_column="writer_id")

class Meta:
db_table = 'book_collection'

What Happens Here? - **Custom column name:** writer id instead of author id. - **Custom
table name:** book collection instead of book. - **ON DELETE SET NULL:** Agar **author
delete hota hai**, toh **book ka foreign key NULL ho jayega** instead of getting deleted.
---
Final Notes: - Foreign key ke liye **Django by default " id" suffix lagata hai** table
me, par Python code me nahi. - Queries me **foreign key ka field name hi use hota hai**
(e.g., book.author), na ki **database column name (e.g., author id)**. - **Best practices
follow karein** taaki future me readability aur maintainability achhi rahe.
=============================== ===============================
Understanding Foreign Keys and Primary Keys in Django

Scenario Description
Agar user id ek field hai Django model me aur yeh kisi **dusre table ko reference** karta
hai (e.g., UserSettings), toh iska **matlab yeh hai ki** user id **foreign key hai**, jo
UserSettings table ke **primary key** (jo ki id ya uuid ho sakti hai) ko store karega.
Key Points: - Har table ka ek **primary key (PK)** hota hai jo **uniquely identify
karta hai har row**. - Jab ek **foreign key (FK)** kisi **dusre table ke PK ko reference
karti hai**, toh tables ke beech **relationship establish hota hai**. - **Foreign key ka
datatype PK ke datatype ke sath match hona chahiye** (e.g., agar PK UUID hai toh FK bhi
UUID hoga).
---

Model Example
import uuid
from django.db import models

class UserSettings(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user_name = models.CharField(max_length=255)

33
class SomeOtherModel(models.Model):
user_id = models.ForeignKey(UserSettings, on_delete=models.CASCADE)

Explanation: - **UserSettings Table:** - **uuid** ek **primary key hai** aur UUID format
me store hoti hai. - **user name** ek simple text field hai.
- **SomeOtherModel Table:** - **user id** ek **foreign key hai**, jo UserSettings ke
**uuid primary key** ko reference karta hai. - Agar **UserSettings ka ek row delete hota
hai**, toh **uska related row bhi delete ho jayega** (on delete=models.CASCADE ki wajah
se).
---

What Happens?
• user id field in SomeOtherModel will store the **primary key value** of the corresponding
row from UserSettings.

• Agar **UserSettings ka primary key UUID hai**, toh user id field bhi **UUID store karega**.
• Agar **UserSettings ka primary key integer ID hai**, toh user id field bhi **integer
store karega**.

Table Name Columns


Example Table Structure (When Using UUID as Primary Key): user settings uuid (Primary Key)
some other model id (Primary Key),
Important Notes: - Agar aap **UUIDField ko primary key banate hain**, toh **ForeignKey
bhi UUIDField ka reference lega**. - Agar aap default id (integer) primary key use karte
hain, toh **foreign key bhi integer store karega**. - **on delete=models.CASCADE ka matlab
hai ki** agar UserSettings ka ek row delete hota hai, toh **uska corresponding row bhi SomeOtherModel
me delete ho jayega**.
---

Real-World Example
Agar ek **UserSettings table** me **users ke preferences store ho rahe hain**, aur ek **SomeOtherMode
table** me users ke related records ho, toh:

# UserSettings Table (UUID Primary Key)


| uuid | user_name |
|---------------------------------------|------------|
| 550e8400-e29b-41d4-a716-446655440000 | Alice |
| 123e4567-e89b-12d3-a456-426614174000 | Bob |

# SomeOtherModel Table (Foreign Key referencing UserSettings)


| id | user_id |
|-----|--------------------------------------|
| 1 | 550e8400-e29b-41d4-a716-446655440000 |
| 2 | 123e4567-e89b-12d3-a456-426614174000 |

Agar Alice ka record delete hota hai, toh uska **related row bhi SomeOtherModel me delete
ho jayega** because of **CASCADE**.
---

Querying the Data


Fetch related data:

# Fetch user settings for a specific entry


obj = SomeOtherModel.objects.get(id=1)
print(obj.user_id) # Prints UUID of UserSettings record
print(obj.user_id.user_name) # Prints 'Alice'

34
Explanation: - **obj.user id** → UserSettings ka UUID return karega. - **obj.user id.user name**
→ Directly related user ka naam fetch karega.
=============================== ===============================
Understanding the Relationship Between Tables Through For-
eign Keys
main courselicense table mein do foreign keys hain|
main courselicense course id id 2b75b991 fk main course uuid aur main courselicense project id id be1553
yeh dikhata hai ki main courselicense table main course aur main project tables ke saath
linked hai in foreign keys ke zariye. Yeh iska matlab hai:
1. main courselicense course id id 2b75b991 fk main course uuid:
- Yeh foreign key main course table mein ek record ko refer karta hai.
- Yeh ek Course License ko ek specific Course (jo main course table mein hai) se link karta
hai.
- Iska matlab hai ki main courselicense table ka har entry ek specific course ke saath associated
hai
(through main course table).
2. main courselicense project id id be155323 fk main project uuid:
- Yeh foreign key main project table mein ek record ko refer karta hai.
- Yeh ek Course License ko ek specific Project (jo main project table mein hai) se link
karta hai.
- Iska matlab hai ki main courselicense table ka har entry ek specific project ke saath
associated hai
(through main project table).
Understanding the Relationship:
- main courselicense table ek license ko represent karta hai jo kisi specific project aur
course ke saath associated ho sakta hai.
- Yeh do foreign keys yeh dikhate hain: - Ek Course License ek specific Course ke saath
tied ho sakta hai
(main courselicense course id id 2b75b991 fk main course uuid ke zariye, jo main course table
ko reference karta hai). - Ek Course License ek specific Project ke saath bhi tied ho sakta
hai
(main courselicense project id id be155323 fk main project uuid ke zariye, jo main project
table ko reference karta hai).
Example in Database Terms:
Isse ek example ke zariye samajhte hain: - Course: Ek course ek training module, class,
ya lesson ho sakta hai, jo main course table mein represent hota hai. - Project: Ek project
ek initiative ya courses ka collection ho sakta hai jo ek specific goal ya activity ke related
ho, jo main project table mein represent hota hai. - Course License: Ek license jo kisi
specific course ya project ke liye hota hai aur ek user ya group ko access deta hai.
Aapke database mein: - main courselicense course id id 2b75b991 fk main course uuid main course
table se course ka ID rakhta hoga. - main courselicense project id id be155323 fk main project uuid
main project table se project ka ID rakhta hoga.
Foreign Key Example in Django Models:
Isse aur clarify karne ke liye, yeh foreign keys Django models mein kuch is tarah represent
ho sakte hain:

class MainCourse(models.Model):
name = models.CharField(max_length=100)

class MainProject(models.Model):
name = models.CharField(max_length=100)

class CourseLicense(models.Model):
course = models.ForeignKey(MainCourse, on_delete=models.CASCADE)
project = models.ForeignKey(MainProject, on_delete=models.CASCADE)

35
Key Points:
1. main courselicense course id id 2b75b991 fk main course uuid: Foreign key jo MainCourse
table ko reference karta hai.
2. main courselicense project id id be155323 fk main project uuid: Foreign key jo MainProject
table ko reference karta hai.
3. Yeh relationships ensure karte hain ki har course license MainCourse table mein ek course
aur MainProject table mein ek project ke saath linked ho.
=============================== ===============================
Understanding Foreign Key in Django Models

Explanation of the Line:=Understanding Foreign Key in Django


Models
project_id = models.ForeignKey("Project", on_delete=models.CASCADE, null=True,
blank=True, related_name="project_id")

What Does This Line Do?


• Field Definition:

– Ye line ek foreign key relationship banati hai current model (jaise UserSettings)
aur Project model ke beech.

– project id field current model mein Project table ke primary key (id) ko store
karta hai.

• Behavior:
– on delete=models.CASCADE: Agar referenced Project delete ho jata hai, toh current
table (jaise UserSettings) ke saare rows jo usse refer karte hain, wo bhi delete
ho jayenge.
– null=True: project id field NULL value rakh sakta hai (matlab koi associated Project
nahi hai).
– blank=True: Django forms mein is field ko khali chhodna allowed hai.
– related name="project id": Ye reverse relationship ka naam define karta hai. Project
model se, aap project id use karke specific project se related saare UserSettings
access kar sakte hain.

• Stored Data:
– project id field referenced Project ka primary key (ID) store karta hai. Ye typically
ek integer hota hai.

Data Stored in project id:

id project name
1 P rojectAlpha
2 P rojectBeta

Phir current table (jaise UserSettings) mein, project id ye store karega:

id project id other fields


1 1 ...
2 2 ...

36
Example for Better Understanding:
Maano aapke paas ek Project table hai aur ek UserSettings table hai. Project table mein
2 projects hain:
• Project Alpha (id = 1)
• Project Beta (id = 2)
Ab agar UserSettings table mein koi entry project id = 1 ke saath hai, toh iska matlab
hai ki wo entry Project Alpha se related hai.
Comparison to the Other Line:
user = models.ForeignKey(User, related_name='settings', on_delete=models.CASCADE
)

Key Differences:
• related name:
– related name="project id": Project model mein, reverse relationship project id
use karega current model ke related rows access karne ke liye.
– related name="settings": User model mein, reverse relationship settings use karega
current model ke related rows access karne ke liye.
• Field Name:
– project id: Ye field specifically projects se related hai.
– user: Ye field specifically users se related hai.

Usage:
For project id:

project = Project.objects.get(id=1)
user_settings = project.project_id.all() # Using the related_name="project_id"

For user:

user = User.objects.get(id=1)
user_settings = user.settings.all() # Using the related_name="settings"

Stored Data:
In project id: Stores the ID of the referenced Project table.
In user: Stores the ID of the referenced User table.
Notes Summary:
project id Field Definition:

project_id = models.ForeignKey("Project", on_delete=models.CASCADE, null=True,


blank=True, related_name="project_id")

• Project table ke saath ek foreign key relationship banata hai.


• Current table mein referenced Project ka id store karta hai.
• Nullable values (null=True) aur empty form fields (blank=True) allow karta hai.
• Agar Project delete ho jata hai, toh current model ke saare related rows bhi delete
ho jate hain (on delete=models.CASCADE).
• Project model mein, reverse relationship ka naam project id hai.

37
Difference Between project id and user:
• Dono ForeignKey fields hain, lekin:

– project id Project table ko reference karta hai, aur uska primary key (id) store
karta hai.
– user User table ko reference karta hai, aur uska primary key (id) store karta hai.
• related name reverse relationship ka naam define karta hai, jisse aap dusre model ke
related rows access kar sakte hain.

Example for Reverse Relationship:


Maano aapke paas ek Project hai jiska id = 1 hai. Agar aap us project se related saare
UserSettings access karna chahte hain, toh aap ye code use kar sakte hain:

project = Project.objects.get(id=1)
user_settings = project.project_id.all()

Isi tarah, agar aapke paas ek User hai jiska id = 1 hai, aur aap us user se related saare
UserSettings access karna chahte hain, toh aap ye code use kar sakte hain:

user = User.objects.get(id=1)
user_settings = user.settings.all()

Conclusion:
Foreign key Django models mein ek powerful feature hai jo aapko tables ke beech relationships
define karne mein madad karta hai. on delete, null, blank, aur related name jaise options
use karke aap apne models ko flexible aur efficient bana sakte hain. Umeed hai ki ye explanation
aur examples aapko foreign key ko samajhne mein madad karenge!
=============================== ===============================
Understanding ProductSerializer in Django (Hinglish Explana-
tion)
Ye code ka explanation line-by-line de raha hoon in simple words:
[colframe=blue!80, colback=gray!5, title=ProductSerializer Code]

class ProductSerializer(serializers.ModelSerializer):
category_name = serializers.CharField(source='category.cat_name', read_only=True)

class Meta:
model = Product
fields = ['id', 'name', 'vendor', 'status', 'activity', 'category', 'required_field'
, 'category_name']

def get_category_name(self, obj):


return obj.category.cat_name

Code Breakdown (Hinglish Explanation):

class ProductSerializer(serializers.ModelSerializer):

- Ye ek naya serializer define kar raha hai jiska naam hai ProductSerializer. - Ye inherit
karta hai serializers.ModelSerializer se, jo Django models ke liye data ko serialize aur
deserialize karne ke kaam aata hai.

category_name = serializers.CharField(source='category.cat_name', read_only=True)

38
- category name: Ek custom field hai jo serializer me add ki gayi hai. Ye Product model
me directly nahi hai. - serializers.CharField: Ye batata hai ki ye field string data rakhegi.
- source=’category.cat name’: - Ye field Category model ke cat name field se value le raha
hai. - Ye possible hai kyunki category ek foreign key hai Product model me. - read only=True:
Ye batata hai ki field sirf output me dikhegi aur request se update/create nahi ho sakti.

class Meta:

- Ye ek nested Meta class hai jo serializer ke baare me metadata provide karta hai, jaise
model kaunsa use ho raha hai aur kaunse fields include karni hain.

model = Product

- Ye specify karta hai ki serializer Product model ke liye banaya gaya hai. - Ye serializer
Product model ke fields aur relationships ka use karega.

fields = ['id', 'name', 'vendor', 'status', 'activity', 'category', 'required_field', '


category_name']

- fields: Ek list hai jo batati hai ki kaunse fields serialized output me dikhengi. -
Ye batata hai serializer ko: - id, name, vendor, status, activity, category, aur required field
ko Product model se directly le. - Saath me category name custom field bhi include kare.

def get_category_name(self, obj):


return obj.category.cat_name

- get category name: Ye ek custom method hai jo category name field ke liye value provide
karta hai. - self: ProductSerializer class ke instance ko refer karta hai. - obj: Product
object ko refer karta hai jo serialize ho raha hai. - return obj.category.cat name: Ye
current product ke liye Category model se cat name ki value retrieve karta hai.
Summary of What the Serializer Does:
• Serializer Product model se linked hai jo uske data ko serialize aur deserialize karta
hai.
• Model ke saath fields bhi use karta hai (id, name, vendor, etc.) aur ek custom field
category name.

• category name field ke liye:


– Category model ke cat name field se value fetch karta hai (via category foreign
key).
– Ye field read-only hai aur API requests se update nahi ho sakti.

• Ye output aur input data structure ko control karta hai Product model ke liye APIs
ke kaam me.

Code Example:

class UserSettingsSerializerALL(serializers.ModelSerializer):
is_active = serializers.BooleanField()

class Meta:
model = UserSettings
fields = " all "
extra_kwargs = {
'password': {'write_only': True}
}

39
Code Line-by-Line Explanation in Hinglish:
1. class UserSettingsSerializerALL(serializers.ModelSerializer):
- Ye ek serializer class hai jo ModelSerializer inherit kar rahi hai. - ModelSerializer
ka matlab hai ki ye class directly ek Django model (UserSettings) ke upar based hai. -
Iska kaam hoga UserSettings model ke data ko JSON me convert karna aur wapas.
---
2. isa ctive = serializers.BooleanF ield()
- Yaha isa ctiveekextra fieldbanayigayihaijomodelmeshayadnahihai, buthumiseserializermeaddkarrahehain.−
BooleanFieldkamatlabhaikiiskavaluesirf TrueyaFalsehosaktahai.
---
3. class Meta:
- Meta ek nested class hai jo serializer ke configuration ke liye hoti hai. - Isme batate
hain ki serializer kis model ke saath kaam karega aur kaunse fields use karega.
---
4. model = UserSettings
- Batata hai ki ye serializer UserSettings model ke saath linked hai. - Matlab, UserSettings
ka data serialize/deserialize karne ke liye ye serializer use hoga.
---
5. fields = " all "
- fields define karta hai ki model ke kaunse fields ko serializer me include karna hai.
- all ka matlab hai model ke saare fields ko include karo.
---
6. extra kwargs = {’password’: {’write only’: True}}
- extra kwargs ek special configuration hai jo kuch fields ke behavior ko customize karne
ke liye use hoti hai. - password field ke liye write only: True ka matlab hai: - Ye field
sirf create aur update operations ke liye use hogi. - Read (fetch) operations me ye field
nahi milegi (security ke liye).
---

Code in Short:
Ye serializer UserSettings model ke saare fields handle karega, lekin:
1. Ek extra field is active add karega (jo True/False hogi).

2. password field ko write-only banayega (sirf set/update karne ke liye, read nahi kar
sakte).
==================================================================================================
Django REST Framework: Custom Serializer Field with SerializerMethodFi
Listing 1: Book Model Definition (Data Source)

1 from django.db import models # Django ke models import kar rahe hain
2
3 class Book(models.Model): # Book ka ek model define kar rahe hain
4 title = models.CharField(max_length=255) # Book ka title, max 255 characters
5 author = models.CharField(max_length=255) # Author ka naam, max 255 characters
6 publication_year = models.IntegerField() # Book ka publication year, integer field
7
8 def str (self): # String representation define karte hain jab object ko print karein
9 return self.title # Title return karega

---

40
Listing 2: Book Serializer Definition (Data Serialization)

1 from rest_framework import serializers # DRF se serializers import karte hain


2 from .models import Book # Book model ko import karte hain jo data source hai
3
4 class BookSerializer(serializers.ModelSerializer):
5 # Serializer banate hain jo Book model ko JSON format me convert karega
6
7 is_classic = serializers.SerializerMethodField()
8 # Ek custom field add kiya `is_classic` jo runtime pe calculate hoga using get_is_classic
9
10 class Meta: # Meta class ke through model aur fields define karte hain
11 model = Book # Ye serializer Book model pe kaam karega
12 fields = ['title', 'author', 'publication_year', 'is_classic']
13 # Output me ye fields include honge: title, author, publication_year, aur is_classic
14
15 def get_is_classic(self, obj):
16 # Custom method hai jo `is_classic` field ki value calculate karega
17 return obj.publication_year < 2000
18 # Agar publication_year 2000 se pehle ka hai toh True return karega, warna False

---
Listing 3: Serializer Usage (Converting Data to JSON)

1 # Ek Book ka object banate hain


2 book = Book(title="The Great Gatsby", author="F. Scott Fitzgerald", publication_year=1925)
3
4 # Serializer ka instance banate hain aur Book object pass karte hain
5 serializer = BookSerializer(book)
6
7 # Serialized data ko print karte hain
8 print(serializer.data) # JSON format me data return karega

---
Listing 4: Serialized Output with Comments

1 {
2 "title": "The Great Gatsby", # Book ka title
3 "author": "F. Scott Fitzgerald", # Book ka author
4 "publication_year": 1925, # Book ka publication year
5 "is_classic": true # Custom field, True kyunki 1925, 2000 se pehle hai
6 }

---
Line-by-Line Explanation in Hinglish
• Model Definition:
– Book: Ek model hai jo database me table banata hai.
– Fields:
∗ title: Book ka naam store karta hai.
∗ author: Author ka naam store karta hai.
∗ publication year: Book kis year me publish hui thi.
• Serializer Definition:
– BookSerializer: Book model ka data JSON me convert karta hai.
– is classic:
∗ Ye ek SerializerMethodField hai jo custom logic ke through value calculate
karta hai.
∗ get is classic: Is field ka value yahan define hota hai.

41
• Serializer Usage:
– Ek Book object lete hain aur uska serializer instance banate hain.
– serializer.data: Serialized JSON data return karta hai.
• Serialized Output:
– Yeh output ka structure hota hai jab serializer ka use hota hai.
– Custom field is classic dynamically calculate hota hai based on condition (publication year
< 2000).
---
Why Use SerializerMethodField?
• Jab kisi field ki value runtime pe calculate karni ho.
• Jaise, yahan humne is classic field add kiya jo model me nahi tha, par JSON output
me chahiye tha.
---
==================================================================================================
Code: Model with str Method

1 from django.db import models


2 from django.db.models import JSONField
3
4 class ReportCustomization(models.Model): # BaseModel ke jagah Django ka Model use karein
5 user_customization = models.ForeignKey(
6 "UserSettings",
7 related_name='user_customization',
8 on_delete=models.CASCADE
9 )
10 report_type = models.CharField(max_length=250, null=True, blank=True)
11 customizations = JSONField(null=True, blank=True)
12
13 # str method to provide string representation
14 def str (self):
15 return self.user_customization.userName # Returning user's name

Explanation in Hinglish
1. Kya hota hai str method?
- str method ka kaam hai object ka human-readable string representation dena. - Jab
bhi aap kisi model ka object query karte ho (e.g., Admin panel me ya shell me), Django isko
as a string represent karta hai.
2. Agar str method diya hai:
- Jab aap ReportCustomization model ka object call karoge, aapko user’s name (user customization.user
dikhega. - Example:

1 obj = ReportCustomization.objects.first()
2 print(obj) # Output: userName (user_customization field ka userName)

3. Agar str method nahi diya (default behavior):


- Django default behavior follow karega, aur object ka string representation kuch aise hoga:

1 <ReportCustomization: ReportCustomization object (1)>

- Example:

1 obj = ReportCustomization.objects.first()
2 print(obj) # Output: <ReportCustomization: ReportCustomization object (1)>

42
4. Admin panel me difference:
- With str : Admin panel me ReportCustomization ka object user-friendly string (e.g.,
userName) me show hoga. - Without str : Admin panel me ReportCustomization object (ID)
show karega, jo debugging ke liye confusing ho sakta hai.

Why Sometimes We Don’t Use str ?


1. Jab zarurat nahi hoti:
- Agar model ka data sirf backend processing ke liye hai, toh str method skip karte hain.
2. Built-in representation sufficient hai:
- Kuch cases me primary key ya default representation kaafi hoti hai.

Consequences If We Don’t Use str :


Admin Panel:
- Admin me objects readable aur understandable nahi lagte:

1 ReportCustomization object (1)


2 ReportCustomization object (2)

Debugging:
- print(object) ya logs me object samajhne me dikkat ho sakti hai.

Summary:
• str ka kaam: Object ka human-readable string representation dena.

• Agar str diya: Output me relevant aur understandable string (e.g., userName) milega.
• Agar nahi diya: Default string format (<ModelName: ModelName object (ID)>) use hoga.
• Best Practice: Human-facing areas (admin, debugging) ke liye str define karein.

Example Comparison:
With str :

1 obj = ReportCustomization.objects.first()
2 print(obj) # Output: userName

Without str :

1 obj = ReportCustomization.objects.first()
2 print(obj) # Output: <ReportCustomization: ReportCustomization object (1)>

==================================================================================================
Django Shell Testing Explained (For Beginners)
If you want to test a specific part of your Django code, like functions, models, or utilities,
you can use the **Django shell**. Below is a beginner-friendly explanation, including folder
structure, step-by-step setup, and examples.
---
Listing 1: Project Folder Structure
Let’s assume you have the following Django project:

43
1 my_django_project/
2 manage.py
3 myapp/
4 init .py
5 models.py # Your database models
6 views.py # Contains functions for HTTP requests
7 tasks.py # Custom utility functions (e.g., business logic)
8 migrations/ # Auto-generated files for database changes
9 my_django_project/
10 init .py
11 settings.py # Configuration file
12 urls.py # Routes HTTP requests to views

---
Listing 2: What is ‘python manage.py shell‘?
The ‘python manage.py shell‘ command allows you to interact with your Django project in
an interactive Python shell.
• It gives access to all models, utilities, and settings in your project.
• You can use it to **test small pieces of code**, **query the database**, or **debug
functions**.
---
Listing 3: How to Use ‘manage.py shell‘
Step 1: Start the Shell Run the following command in your project directory:

1 python manage.py shell

Step 2: Import Your Code Inside the shell, import the function, model, or code you
want to test.

1 # Importing a Function from `tasks.py`


2 from myapp.tasks import my_function
3
4 # Importing a Model from `models.py`
5 from myapp.models import MyModel

Step 3: Run Your Code Call the function or query the database.
---
Listing 4: Simple Code Examples
Example 1: Testing a Function in ‘tasks.py‘

1 # tasks.py
2 def greet_user(name):
3 return f"Hello, {name}!"

Listing 1: tasks.py
Testing in the Shell:

1 python manage.py shell

Inside the shell:

1 from myapp.tasks import greet_user


2 print(greet_user("Alice"))
3 # Output: "Hello, Alice!"

---

44
Example 2: Querying the Database with a Model

1 from django.db import models


2
3 class Book(models.Model):
4 title = models.CharField(max_length=100)
5 author = models.CharField(max_length=100)
6 published_year = models.IntegerField()

Listing 2: models.py

Testing in the Shell:

1 python manage.py shell

Inside the shell:

1 from myapp.models import Book


2
3 # Fetch all books
4 books = Book.objects.all()
5 print(books)
6
7 # Create a new book
8 new_book = Book.objects.create(title="Django for Beginners", author="John Doe", published_year=2024)
9 print(new_book.title)
10
11 # Filter books by author
12 filtered_books = Book.objects.filter(author="John Doe")
13 print(filtered_books)

---
Example 3: Testing an API Call Function

1 import requests
2
3 def fetch_data_from_api(url):
4 response = requests.get(url)
5 if response.status_code == 200:
6 return response.json()
7 return {"error": "Failed to fetch data"}

Listing 3: tasks.py

Testing in the Shell:

1 python manage.py shell

Inside the shell:

1 from myapp.tasks import fetch_data_from_api


2
3 # Test with a public API
4 data = fetch_data_from_api("https://jsonplaceholder.typicode.com/posts")
5 print(data)

---
Listing 5: Bonus: Using ‘shellp lus‘f orAutoImports
If importing manually feels tedious, you can use **‘shellp lus‘∗∗f romthe‘django−extensions‘package :

1 # Install django-extensions
2 pip install django-extensions
3
4 # Add to INSTALLED_APPS in settings.py
5 INSTALLED_APPS += ['django_extensions']

45
6
7 # Run the enhanced shell
8 python manage.py shell_plus

This will auto-import all your models and utilities, saving time.
---
==================================================================================================

What is a Container?
[colback=lightgray!20, colframe=blue!50, title=Definition] A container ek lightweight,
standalone aur executable package hota hai jo kisi bhi application ke run hone ke liye zaroori
sab cheezein contain karta hai:
• Code
• Runtime (like Python, Node.js, etc.)

• System tools and libraries


• Dependencies
[colback=lightgray!10, colframe=blue!40, title=Key Concept] Containers application ko
host system se isolate kar dete hain. Iska matlab hai ki **containerized application har
jagah ek jaisa chalega**, chahe woh laptop ho, server ho, ya cloud ho.
[colback=yellow!10, colframe=red!50, title=Understanding via Example] Ek container ko
aap ek **virtual box** samajh sakte hain jo aapke app ko secure karta hai, **lekin yeh traditional
Virtual Machines (VMs) se kaafi chhota aur fast hota hai** kyunki yeh apna alag OS nahi
chalayega, balki host system ka OS share karega.

What is Docker?
[colback=lightgray!20, colframe=blue!50, title=Definition] Docker ek platform hai jo
containers ko **easily create, manage, aur run karne me madad karta hai**. Yeh tools provide
karta hai:
1. Build: Code se container banane ke liye (Dockerfile ka use karke).

2. Ship: Container ko share ya distribute karne ke liye (Docker Hub ya kisi registry
ke through).
3. Run: Containers ko different environments me consistently execute karne ke liye.
[colback=yellow!10, colframe=red!50, title=Understanding via Analogy] Docker ko ek **factory**
samajh lo jo **containers create aur manage karne ka kaam karti hai**.

Analogy to Understand:
[colback=lightgray!10, colframe=blue!40, title=Real-Life Example]
• Ek **container** ek ready-to-eat meal ki tarah hai (jisme khana, cutlery, aur sab kuch
ready hai).

• **Docker** ek chef aur packaging system hai jo meal ko prepare karta hai aur ensure
karta hai ki **har bar ek jaisa ho**.

46
How They Work Together (Example):
[colback=lightgray!20, colframe=blue!50, title=Without Docker/Containers] Sochiye, aapne
ek Python app develop kiya jo aapke laptop pe perfect chal raha hai. Lekin jab aap ise
kisi server pe run karne ki koshish karte hain, toh errors aate hain kyunki server pe Python
ka version ya libraries install nahi hain.

[colback=yellow!10, colframe=red!50, title=With Docker and Containers]


• Aap Docker ka use karke apne Python app ka ek **container** bana sakte hain.
• Yeh container contain karega:

– App ka code.
– Required Python version.
– Saari zaroori libraries.
• Ab yeh **container kisi bhi jagah run ho sakta hai bina environment dependency ke**.

Why are Containers Useful?


[colback=lightgray!10, colframe=blue!40, title=Key Advantages]
• Portability: "Write once, run anywhere" ka concept implement hota hai.
• Isolation: Har container apni environment maintain karta hai, jo **conflicts prevent
karta hai**.

• Efficiency: Containers **traditional VMs se zyada fast aur lightweight hote hain**.
=============================== ===============================
AWS Notes for Backend Django Developers

1. Amazon S3 (Simple Storage Service)


[colback=lightgray!20, colframe=blue!50, title=What is it?] Amazon S3 ek cloud storage
service hai jo kisi bhi type ke data (files, images, logs, etc.) store karne ke liye use
hoti hai.
[colback=yellow!10, colframe=red!50, title=Key Features]
• Data buckets (folders) me store hota hai.
• Highly scalable aur durable (99.999999999
• Use cases: backups, static website hosting, aur media/data storage.

[colback=lightgray!10, colframe=blue!40, title=Why Django Developers Should Know It]


• Static files aur media uploads ke liye S3 ka use kar sakte hain.
• django-storages ke through S3 integration easily ho sakti hai.

47
2. AWS Glue
[colback=lightgray!20, colframe=blue!50, title=What is it?] AWS Glue ek serverless data
processing tool hai jo data ko prepare aur transform karta hai analytics aur machine learning
ke liye.
[colback=yellow!10, colframe=red!50, title=Key Features]
• Crawler: Data ko scan karke schema create karta hai.
• ETL (Extract, Transform, Load): Data clean ya convert karta hai (e.g., CSV to Parquet).
• S3, Redshift, aur Athena ke saath smoothly kaam karta hai.
[colback=lightgray!10, colframe=blue!40, title=Why Django Developers Should Know It]
• Data cleaning aur analytics ke automation ke liye helpful hai.
• S3 ke saath Glue ka use karke reports ya ML datasets prepare kiye ja sakte hain.

3. AWS Data Pipeline


[colback=lightgray!20, colframe=blue!50, title=What is it?] AWS Data Pipeline ek service
hai jo AWS services aur external systems ke beech data movement aur transformation automate
karti hai.
[colback=yellow!10, colframe=red!50, title=Key Features]
• Workflows automate karta hai (e.g., S3 se Redshift me data copy karna).
• AWS aur non-AWS systems ke beech data transfer possible karta hai.
[colback=lightgray!10, colframe=blue!40, title=Why Django Developers Should Know It]
• Processed data ko transfer karne aur backups automate karne ke liye use hota hai.

4. Parquet File Format


[colback=lightgray!20, colframe=blue!50, title=What is it?] Parquet ek compressed column-based
file format hai jo large datasets store karne ke liye efficient hota hai.
[colback=yellow!10, colframe=red!50, title=Key Features]
• Analytics me fast performance deta hai kyunki sirf required columns read hote hain.
• File size chhoti hoti hai, jo storage cost bachata hai.
• Glue, Spark, aur Athena jese big data tools ke saath commonly use hota hai.
[colback=lightgray!10, colframe=blue!40, title=Why Django Developers Should Know It]
• Large datasets (logs, reports) S3 me efficiently store karne ke liye useful hai.

What AWS Services a Django Backend Developer Should Know


[colback=lightgray!10, colframe=blue!50, title=Essential AWS Services]
1. S3 - Static/media files aur backups ke liye.
2. RDS - Managed PostgreSQL/MySQL databases.
3. EC2 - Django apps deploy karne ke liye.
4. Elastic Beanstalk - Easy deployment ke liye.
5. AWS Lambda - Background tasks aur automation ke liye.

48
6. CloudWatch - Logging aur monitoring ke liye.
7. IAM - AWS security aur access management.
8. AWS Secrets Manager - Securely credentials store karne ke liye.

Code Example: Using S3 with Django


[colback=lightgray!10, colframe=blue!50, title=settings.py Configuration for S3]

# settings.py configuration for S3 storage using django-storages

INSTALLED_APPS = [
'storages',
]

AWS_ACCESS_KEY_ID = '<your-access-key>'
AWS_SECRET_ACCESS_KEY = '<your-secret-key>'
AWS_STORAGE_BUCKET_NAME = '<your-bucket-name>'
# Static files (CSS, JavaScript, images)
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/'

# Media files
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/'

=============================== ===============================
article xcolor listings tcolorbox
outputbox colback=outputbg, boxrule=0pt, arc=0pt, outer arc=0pt, top=2pt, bottom=2pt,
left=2pt, right=2pt

Git Commands
Yeh guide aapko most commonly used Git commands ko Hinglish mein samjhata hai, unke kaam
aur ek chhota sa example Git stash command ka bhi deta hai.
Common Git Commands:
1. git init
Kya karta hai: Ek nayi Git repository create karta hai.
Use kahan hota hai: Jab naye project ko version control mein lana ho.
Example:

git init

Initialized empty Git repository in /path/to/your/repo/.git/

2. git clone
Kya karta hai: Ek remote repository ka copy local machine par download karta hai.
Example:

git clone https://github.com/username/repository.git

Cloning into ’repository’...


remote: Enumerating objects: 100, done.
remote: Counting objects: 100% (100/100), done.
remote: Compressing objects: 100% (80/80), done.
Receiving objects: 100% (100/100), 10.00 MiB | 1.00 MiB/s, done.
Resolving deltas: 100% (20/20), done.

49
3. git add
Kya karta hai: Files ko staging area mein le jaata hai, taaki commit ke liye ready ho.
Example:

git add file.txt


git add .

(No output if successful)

4. git commit
Kya karta hai: Changes ko save karta hai Git repository mein.
Example:

git commit -m "Yeh mera first commit hai"

[main (root-commit) abc1234] Yeh mera first commit hai


1 file changed, 1 insertion(+)
create mode 100644 file.txt

5. git status
Kya karta hai: Current repository ka status dikhata hai (kaunsi files change hui hain,
staged hain, etc.).
Example:

git status

On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: file.txt

6. git log
Kya karta hai: Commit history dikhata hai.
Example:

git log

commit abc1234 (HEAD -> main)


Author: Your Name <[email protected]>
Date: Mon Oct 2 12:00:00 2023 +0530

Yeh mera first commit hai

7. git pull
Kya karta hai: Remote repository ke latest changes ko apne local repository mein download
aur merge karta hai.
Example:

git pull origin main

remote: Enumerating objects: 5, done.


remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (3/3), done.
Unpacking objects: 100% (3/3), 1.00 KiB | 1.00 MiB/s, done.
From https://github.com/username/repository
* branch main -> FETCH_HEAD

50
abc1234..def5678 main -> origin/main
Updating abc1234..def5678
Fast-forward
file.txt | 1 +
1 file changed, 1 insertion(+)

8. git push
Kya karta hai: Apne local repository ke changes ko remote repository mein upload karta
hai.
Example:

git push origin main

Enumerating objects: 5, done.


Counting objects: 100% (5/5), done.
Writing objects: 100% (3/3), 300 bytes | 300.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To https://github.com/username/repository.git
abc1234..def5678 main -> main

9. git branch
Kya karta hai: Naye branch banata hai ya branches ka list dikhata hai.
Example:

git branch
git branch new-feature

* main
new-feature

10. git checkout


Kya karta hai: Branch switch karne ke liye ya kisi specific commit par kaam karne ke liye
use hota hai.
Example:

git checkout new-feature

Switched to branch ’new-feature’

11. git merge


Kya karta hai: Ek branch ke changes ko dusre branch mein merge karta hai.
Example:

git merge new-feature

Updating abc1234..def5678
Fast-forward
file.txt | 1 +
1 file changed, 1 insertion(+)

12. git stash


Kya karta hai: Apke changes ko temporarily save karta hai bina commit kare, taaki aap
baad mein wapas le sako.
Example:

git stash

51
Saved working directory and index state WIP on main: abc1234 Yeh mera first commit hai

13. git remote


Kya karta hai: Remote repository ko manage karne ke liye commands deta hai.
Example:

git remote add origin https://github.com/username/repository.git

(No output if successful)

14. git diff


Kya karta hai: Changes ko compare karta hai (unstaged ya staged).
Example:

git diff

diff --git a/file.txt b/file.txt


index abc1234..def5678 100644
--- a/file.txt
+++ b/file.txt
@@ -1 +1,2 @@
Hello World
+New changes

Git Stash - Small Example


Scenario: Aap kisi file mein kaam kar rahe ho, aur achanak aapko ek aur urgent branch
par kaam karna padta hai.
Lekin aapko current changes ko commit nahi karna.
Steps:
1. Apni file mein changes karo:

echo "Naye changes add kiye" >> file.txt

2. Check karo ki file modify hui hai:

git status

On branch main
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: file.txt

3. Changes ko stash mein daalo:

git stash

Saved working directory and index state WIP on main: abc1234 Yeh mera first commit hai

4. Ab branch switch karo:

git checkout new-feature

Switched to branch ’new-feature’

52
5. Jab kaam complete ho jaye, apne changes ko wapas lao:

git stash apply

On branch new-feature
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: file.txt

6. Stash ko delete kar do agar wapas nahi chahiye:

git stash drop

Dropped refs/stash@{0} (abc1234...)

Important Notes:
Git stash useful hai jab aap apne changes ko commit kiye bina temporarily save karna chahte
hain. Multiple stashes ko save karne ke liye:

git stash save "Mera first stash"

=============================== ===============================
Vs Code Tricks === Searching within Selected Lines
Jab aap 10 lines of code select karte hain aur Ctrl+F (ya Cmd+F Mac par) dabate hain, to
search sirf selected text par apply hota hai.
Agar aap ise pure function par apply karna chahte hain (bina manually select kiye), to
aap ye kar sakte hain:
1. Editor ke "Select Function" option ka use kare (modern code editors mein available
hai).
2. Ya phir keyboard shortcuts ka use karke selection ko function level tak expand kare
(IDE/editor ke hisab se alag ho sakta hai).
3. Function select karne ke baad, Ctrl+F (ya Cmd+F) dabakar sirf function ke andar search
kare.
================================================

Django update or create Function


Django mein update or create function ek shortcut method hai jo:
1. Update karta hai agar object exist karta hai, ya
2. Create karta hai agar object exist nahi karta.

Syntax

Model.objects.update_or_create(defaults=None, **kwargs)

• kwargs: Database mein object ko dhoondhne ke liye use hone wale fields.
• defaults: Object ko update karne ke liye use hone wale fields (agar mil gaya) ya naye
object ke liye values set karne ke liye (agar create karna hai).

53
Key Points
1. Returns a Tuple:
• (object, created) jahan:
– object: Updated ya created object.
– created: Ek boolean (True agar create hua, False agar update hua).
2. Atomic:
• Operation ko safe rakhta hai aur race conditions se bachata hai.
3. Useful For:
• Duplicate data se bachne ke liye.
• Consistent updates ya inserts ensure karne ke liye.

Example 1: Basic Usage

from myapp.models import User

# Update kare agar username 'john' wala user exist karta hai; create kare agar nahi.
user, created = User.objects.update_or_create(
username='john', # Lookup field
defaults={'email': '[email protected]', 'first_name': 'John'}
)

if created:
print("User created:", user)
else:
print("User updated:", user)

Example 2: No defaults

# Sirf specific fields ko update kare


user, created = User.objects.update_or_create(
username='jane',
defaults={'email': '[email protected]'}
)

What Happens Internally?


1. Lookup Phase:
• Django kwargs ka use karke database mein object dhoondhta hai (e.g., username=’john’).
2. Update or Create Phase:
• Agar mil gaya: defaults mein diye gaye fields ko update karta hai.
• Agar nahi mila: kwargs aur defaults mein diye gaye fields ke saath naya object
create karta hai.

Example Output
• Agar username=’john’ wala user exist karta hai:
– email aur first name ko update karta hai.
– created = False return karta hai.
• Agar aisa koi user exist nahi karta:
– username, email, aur first name ke saath naya user create karta hai.
– created = True return karta hai.

54
Notes for Quick Reference
• Use Cases: Upsert operations (update + insert) ke liye ideal hai.
• Atomicity: Multi-threaded environments mein data inconsistencies se bachata hai.

• Defaults: Fields ko set ya update karne ke liye use kare.

=============================== ===============================

55

You might also like