Django Request Debugging Guide
Django Request Debugging Guide
ber...
Explanation:
• GET - Query parameters ko store karta hai (e.g., ?search=django).
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:
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.
- 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.
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)
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)
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')
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:
• 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.
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.
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]}
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
(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.
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_')}
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
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.
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}")
• 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:
• user id = 6
• task index = 2
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
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
• 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.
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
• 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.
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
@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
__all__ = ('celery_app',)
# 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.
# myapp/tasks.py
from celery import shared_task
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.
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
]
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.
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).
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)
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.
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.
Explanation: env name virtual environment ka folder name hota hai (e.g., env).
Example:
python -m venv myenv
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
Example:
pip install django
18
6. Install Packages from requirements.txt
Example Workflow
1. Ek project folder banayein aur usme navigate karein:
mkdir my_project
cd my_project
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.
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
- 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.
- 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')
- 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)
21
4. Delete (Records Remove Karna)
Delete Ek Single Record
user = User.objects.get(username='JohnDoe')
user.delete()
- filter(): Jo records delete karne hain unko select karega. - delete(): Sab selected
records delete kar dega.
- aggregate(): Fields par calculations karta hai jaise Avg, Max, Sum.
Annotate
users_with_groups = User.objects.annotate(group_count=Count('groups'))
- 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.
- 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()
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
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
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
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.
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()
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)
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.
tasks = Task.objects.filter(
Q(user username='JohnDoe') | Q(status='completed')
)
tasks = Task.objects.filter(
Q(user username in=usernames) & Q(status in=statuses)
)
Explanation:
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]
Step-by-Step Explanation:
• ‘Q(order products name in=productl ist)‘ :
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.
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()
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"
class BlogPost(models.Model):
title = models.CharField(max_length=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:
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:
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:
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)
---
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)
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**:
---
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**.
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:
Agar Alice ka record delete hota hai, toh uska **related row bhi SomeOtherModel me delete
ho jayega** because of **CASCADE**.
---
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
– 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.
id project name
1 P rojectAlpha
2 P rojectBeta
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:
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.
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']
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.
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: 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.
- 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.
• 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)
---
Listing 3: Serializer Usage (Converting Data to JSON)
---
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
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)
- 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.
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:
Step 2: Import Your Code Inside the shell, import the function, model, or code you
want to test.
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:
---
44
Example 2: Querying the Database with a Model
Listing 2: models.py
---
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
---
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.)
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.
– App ka code.
– Required Python version.
– Saari zaroori libraries.
• Ab yeh **container kisi bhi jagah run ho sakta hai bina environment dependency ke**.
• Efficiency: Containers **traditional VMs se zyada fast aur lightweight hote hain**.
=============================== ===============================
AWS Notes for Backend Django Developers
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.
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.
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
2. git clone
Kya karta hai: Ek remote repository ka copy local machine par download karta hai.
Example:
49
3. git add
Kya karta hai: Files ko staging area mein le jaata hai, taaki commit ke liye ready ho.
Example:
4. git commit
Kya karta hai: Changes ko save karta hai Git repository mein.
Example:
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
7. git pull
Kya karta hai: Remote repository ke latest changes ko apne local repository mein download
aur merge karta hai.
Example:
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:
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
Updating abc1234..def5678
Fast-forward
file.txt | 1 +
1 file changed, 1 insertion(+)
git stash
51
Saved working directory and index state WIP on main: abc1234 Yeh mera first commit hai
git diff
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
git stash
Saved working directory and index state WIP on main: abc1234 Yeh mera first commit hai
52
5. Jab kaam complete ho jaye, apne changes ko wapas lao:
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
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:
=============================== ===============================
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.
================================================
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.
# 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
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.
=============================== ===============================
55