Working With Linked Lists in Python (Course)
Enroll Free: https://realpython.com/videos/working-linked-lists-overview/
Enroll Free: https://realpython.com/videos/working-linked-lists-overview/
#python #programming #developer #programmer #coding #coder #softwaredeveloper #computerscience #webdev #webdeveloper #webdevelopment #pythonprogramming #pythonquiz #ai #ml #machinelearning #datascience
https://t.me/DataScience4
π4β€1
Pagination in Django
https://testdriven.io/blog/django-pagination/
Looks at how to add pagination to a Django project.
https://testdriven.io/blog/django-pagination/
Looks at how to add pagination to a Django project.
#python #programming #developer #programmer #coding #coder #softwaredeveloper #computerscience #webdev #webdeveloper #webdevelopment #pythonprogramming #pythonquiz #ai #ml #machinelearning #datascience #django
https://t.me/DataScience4
π5π₯1
Django Features and Libraries - course
Exploring Django Features and Libraries
The "Django Features and Libraries" course is designed to help learners deepen their understanding of Django by exploring its advanced features and built-in libraries. Django is a high-level Python web framework that promotes rapid development and clean, pragmatic design. This course provides hands-on experience in leveraging Djangoβs powerful tools to build scalable, efficient, and secure web applications.
Enroll Free: https://www.coursera.org/learn/django-features-libraries
Exploring Django Features and Libraries
The "Django Features and Libraries" course is designed to help learners deepen their understanding of Django by exploring its advanced features and built-in libraries. Django is a high-level Python web framework that promotes rapid development and clean, pragmatic design. This course provides hands-on experience in leveraging Djangoβs powerful tools to build scalable, efficient, and secure web applications.
Enroll Free: https://www.coursera.org/learn/django-features-libraries
#python #programming #developer #programmer #coding #coder #softwaredeveloper #computerscience #webdev #webdeveloper #webdevelopment #pythonprogramming #pythonquiz #ai #ml #machinelearning #datascience #django
https://t.me/DataScience4
π6
Data Management With Python, SQLite, and SQLAlchemy
In this tutorial, youβll learn how to use:
1β£ Flat files for data storage
π’ SQL to improve access to persistent data
π’ SQLite for data storage
π’ SQLAlchemy to work with data as Python objects
Enroll Free: https://realpython.com/python-sqlite-sqlalchemy/
In this tutorial, youβll learn how to use:
Enroll Free: https://realpython.com/python-sqlite-sqlalchemy/
#python #programming #developer #programmer #coding #coder #softwaredeveloper #computerscience #webdev #webdeveloper #webdevelopment #pythonprogramming #pythonquiz #ai #ml #machinelearning #datascience #django #SQLAlchemy #SQLite #SQL
https://t.me/DataScience4
Please open Telegram to view this post
VIEW IN TELEGRAM
π8
ππΊ Interacting With REST APIs and Python [Video]
https://realpython.com/courses/interacting-rest-apis-python/
#Python #RESTAPI #APIsWithPython #WebDevelopment #PythonTutorial #RealPython #BackendDevelopment #HTTPRequests #APIIntegration #LearnPython
https://realpython.com/courses/interacting-rest-apis-python/
#Python #RESTAPI #APIsWithPython #WebDevelopment #PythonTutorial #RealPython #BackendDevelopment #HTTPRequests #APIIntegration #LearnPython
βοΈ Our Telegram channels: https://t.me/addlist/0f6vfFbEMdAwODBkπ± Our WhatsApp channel: https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
Please open Telegram to view this post
VIEW IN TELEGRAM
β€1
Topic: Django Models and ORM β From Basics to Advanced Queries
---
What is a Model in Django?
β’ A model in Django is a Python class that defines the structure of your database table. Each model maps to a table, and each attribute represents a column.
β’ Django uses its ORM (Object-Relational Mapping) to interact with the database using Python code instead of SQL.
---
Creating Your First Model
---
Making Migrations
β’ Create and apply migrations to sync models with the database:
---
Using the Model
---
Model Field Types
β’ CharField, TextField, IntegerField, FloatField, DateField, DateTimeField, BooleanField, EmailField, and more.
---
Meta Class for Model Options
---
Relationships Between Models
β’ One-to-Many (ForeignKey)
β’ Many-to-Many (ManyToManyField)
β’ One-to-One (OneToOneField)
---
Advanced ORM Queries
---
Summary
β’ Django models define your database structure.
β’ The ORM allows you to query and manipulate data using Python.
β’ Supports relationships, complex filtering, ordering, and aggregation.
---
Exercise
β’ Create two models:
1. Add a new book.
2. List all books by a specific author.
3. Delete books published before the year 2000.
---
#Django #WebDevelopment #ORM #DatabaseModels #DjangoTips
https://t.me/DataScience4
---
What is a Model in Django?
β’ A model in Django is a Python class that defines the structure of your database table. Each model maps to a table, and each attribute represents a column.
β’ Django uses its ORM (Object-Relational Mapping) to interact with the database using Python code instead of SQL.
---
Creating Your First Model
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField()
pages = models.IntegerField()
---
Making Migrations
β’ Create and apply migrations to sync models with the database:
python manage.py makemigrations
python manage.py migrate
---
Using the Model
# Creating a new record
book = Book(title="1984", author="George Orwell", published_date="1949-06-08", pages=328)
book.save()
# Fetching all books
books = Book.objects.all()
# Filtering
orwell_books = Book.objects.filter(author="George Orwell")
# Getting one object
book = Book.objects.get(id=1)
# Updating
book.title = "Animal Farm"
book.save()
# Deleting
book.delete()
---
Model Field Types
β’ CharField, TextField, IntegerField, FloatField, DateField, DateTimeField, BooleanField, EmailField, and more.
---
Meta Class for Model Options
class Book(models.Model):
title = models.CharField(max_length=200)
class Meta:
ordering = ['title'] # default ordering by title
---
Relationships Between Models
β’ One-to-Many (ForeignKey)
β’ Many-to-Many (ManyToManyField)
β’ One-to-One (OneToOneField)
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
---
Advanced ORM Queries
# Complex filters
books = Book.objects.filter(published_date__year__gte=2000, pages__lte=300)
# Exclude
books = Book.objects.exclude(author="J.K. Rowling")
# Ordering
books = Book.objects.order_by("-published_date")
# Count
total = Book.objects.count()
---
Summary
β’ Django models define your database structure.
β’ The ORM allows you to query and manipulate data using Python.
β’ Supports relationships, complex filtering, ordering, and aggregation.
---
Exercise
β’ Create two models:
Author and Book. Link them using a foreign key. Then, write views that:1. Add a new book.
2. List all books by a specific author.
3. Delete books published before the year 2000.
---
#Django #WebDevelopment #ORM #DatabaseModels #DjangoTips
https://t.me/DataScience4
β€4
Topic: Django ORM β Advanced Queries, Aggregations, and Query Optimization (Part 2)
---
1. Aggregation Functions
β’ Django provides built-in functions for aggregating data.
---
2. Grouping and Annotating
β’ annotate() is used to compute values for each row (e.g., totals per group).
---
3. Complex Lookups with Q Objects
β’ Use Q for OR, AND, and NOT conditions.
---
4. Selecting Specific Fields
β’ Use values() or values\_list() to retrieve specific fields.
---
5. Related Model Queries
β’ Use select\_related and prefetch\_related to optimize related data access.
---
6. Raw SQL Queries (When Necessary)
---
7. Performance Tips
β’ Use only() or defer() to limit retrieved fields.
β’ Avoid chaining queries in loops.
β’ Use bulk\_create, bulk\_update for inserting/updating many records.
---
Summary
β’ Use aggregate(), annotate(), and Q objects for powerful filtering.
β’ Fetch only what you need using values, only, and select\_related.
β’ Optimize queries by reducing database hits and using Djangoβs ORM efficiently.
---
Exercise
β’ Write a Django query that returns all authors with more than 5 books, sorted by the number of books (descending). Then print their name and book count.
---
#Django #ORM #AdvancedQueries #QueryOptimization #WebDevelopment
https://t.me/DataScience4
---
1. Aggregation Functions
β’ Django provides built-in functions for aggregating data.
from django.db.models import Avg, Sum, Max, Min, Count
# Average number of pages
avg_pages = Book.objects.aggregate(Avg("pages"))
# Total number of pages
total_pages = Book.objects.aggregate(Sum("pages"))
# Count of books per author
book_counts = Book.objects.values("author").annotate(total=Count("id"))
---
2. Grouping and Annotating
β’ annotate() is used to compute values for each row (e.g., totals per group).
# Number of books per author
from django.db.models import Count
authors = Author.objects.annotate(book_count=Count("book"))
for author in authors:
print(author.name, author.book_count)
---
3. Complex Lookups with Q Objects
β’ Use Q for OR, AND, and NOT conditions.
from django.db.models import Q
# Books with title containing 'war' OR author name 'Leo Tolstoy'
books = Book.objects.filter(Q(title__icontains="war") | Q(author__name="Leo Tolstoy"))
# Books not published in 2023
books = Book.objects.filter(~Q(published_date__year=2023))
---
4. Selecting Specific Fields
β’ Use values() or values\_list() to retrieve specific fields.
# Dictionary of titles and authors
data = Book.objects.values("title", "author__name")
# List of titles
titles = Book.objects.values_list("title", flat=True)
---
5. Related Model Queries
β’ Use select\_related and prefetch\_related to optimize related data access.
# Optimized: Single JOIN query for ForeignKey
books = Book.objects.select_related("author")
# For ManyToMany or reverse relations
authors = Author.objects.prefetch_related("book_set")
---
6. Raw SQL Queries (When Necessary)
books = Book.objects.raw("SELECT * FROM myapp_book WHERE pages > %s", [300])
for book in books:
print(book.title)---
7. Performance Tips
β’ Use only() or defer() to limit retrieved fields.
books = Book.objects.only("title")β’ Avoid chaining queries in loops.
β’ Use bulk\_create, bulk\_update for inserting/updating many records.
---
Summary
β’ Use aggregate(), annotate(), and Q objects for powerful filtering.
β’ Fetch only what you need using values, only, and select\_related.
β’ Optimize queries by reducing database hits and using Djangoβs ORM efficiently.
---
Exercise
β’ Write a Django query that returns all authors with more than 5 books, sorted by the number of books (descending). Then print their name and book count.
---
#Django #ORM #AdvancedQueries #QueryOptimization #WebDevelopment
https://t.me/DataScience4
β€2π2
π Comprehensive Guide: How to Prepare for a Django Job Interview β 400 Most Common Interview Questions
Are you ready to get a job: https://hackmd.io/@husseinsheikho/django-mcq
#DjangoInterview #Python #WebDevelopment #Django #BackendDevelopment #RESTAPI #Database #Security #Scalability #DevOps #InterviewPrep
Are you ready to get a job: https://hackmd.io/@husseinsheikho/django-mcq
#DjangoInterview #Python #WebDevelopment #Django #BackendDevelopment #RESTAPI #Database #Security #Scalability #DevOps #InterviewPrep
β€6
# Django ORM Comparison - Know both frameworks
# Django model (contrast with SQLAlchemy)
from django.db import models
class Department(models.Model):
name = models.CharField(max_length=50)
class Employee(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
# Django query (similar but different syntax)
Employee.objects.filter(department__name="HR").select_related('department')
# Async ORM - Modern Python requirement
# Requires SQLAlchemy 1.4+ and asyncpg
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
async_engine = create_async_engine(
"postgresql+asyncpg://user:pass@localhost/db",
echo=True,
)
async_session = AsyncSession(async_engine)
async with async_session.begin():
result = await async_session.execute(
select(Employee).where(Employee.name == "Alice")
)
employee = result.scalar_one()
# Testing Strategies - Interview differentiator
from unittest import mock
# Mock database for unit tests
with mock.patch('sqlalchemy.create_engine') as mock_engine:
mock_conn = mock.MagicMock()
mock_engine.return_value.connect.return_value = mock_conn
# Test your ORM-dependent code
create_employee("Test", "test@company.com")
mock_conn.execute.assert_called()
# Production Monitoring - Track slow queries
from sqlalchemy import event
@event.listens_for(engine, "before_cursor_execute")
def before_cursor(conn, cursor, statement, params, context, executemany):
conn.info.setdefault('query_start_time', []).append(time.time())
@event.listens_for(engine, "after_cursor_execute")
def after_cursor(conn, cursor, statement, params, context, executemany):
total = time.time() - conn.info['query_start_time'].pop(-1)
if total > 0.1: # Log slow queries
print(f"SLOW QUERY ({total:.2f}s): {statement}")
# Interview Power Move: Implement caching layer
from functools import lru_cache
class CachedEmployeeRepository(EmployeeRepository):
@lru_cache(maxsize=100)
def get_by_id(self, employee_id):
return super().get_by_id(employee_id)
def invalidate_cache(self, employee_id):
self.get_by_id.cache_clear()
# Reduces database hits by 70% in read-heavy applications
# Pro Tip: Schema versioning in CI/CD pipelines
# Sample .gitlab-ci.yml snippet
deploy_db:
stage: deploy
script:
- alembic upgrade head
- pytest tests/db_tests.py # Verify schema compatibility
only:
- main
# Real-World Case Study: E-commerce inventory system
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True)
sku = Column(String(20), unique=True)
stock = Column(Integer, default=0)
# Atomic stock update (prevents race conditions)
def decrement_stock(self, quantity, session):
result = session.query(Product).filter(
Product.id == self.id,
Product.stock >= quantity
).update({"stock": Product.stock - quantity})
if not result:
raise ValueError("Insufficient stock")
# Usage during checkout
product.decrement_stock(2, session)
By: @DATASCIENCE4 π
#Python #ORM #SQLAlchemy #Django #Database #BackendDevelopment #CodingInterview #WebDevelopment #TechJobs #SystemDesign #SoftwareEngineering #DataEngineering #CareerGrowth #APIs #Microservices #DatabaseDesign #TechTips #DeveloperTools #Programming #CareerTips
β€3
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename, "content_type": file.content_type}β’ Set a response cookie.
from fastapi import Response
@app.post("/cookie/")
def create_cookie(response: Response):
response.set_cookie(key="fakesession", value="fake-cookie-session-value")
return {"message": "Cookie set"}
β’ Read a request cookie.
from fastapi import Cookie
@app.get("/read-cookie/")
def read_cookie(fakesession: Optional[str] = Cookie(None)):
return {"session": fakesession}
X. Error Handling & Advanced Responses
β’ Handle
HTTPException.from fastapi import HTTPException
@app.get("/items/{item_id}")
def read_item(item_id: str):
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
β’ Return a custom
JSONResponse.from fastapi.responses import JSONResponse
@app.get("/custom/")
def custom_response():
return JSONResponse(status_code=202, content={"message": "Accepted"})
β’ Return an
HTMLResponse.from fastapi.responses import HTMLResponse
@app.get("/page", response_class=HTMLResponse)
def read_page():
return "<h1>Hello World</h1>"
β’ Define a WebSocket endpoint.
from fastapi import WebSocket
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
await websocket.send_text("Hello from WebSocket")
await websocket.close()
β’ Handle a path operation that may not exist.
@app.get("/{full_path:path}")
def read_catch_all(full_path: str):
return {"path": full_path}β’ Mount a static files directory.
from fastapi.staticfiles import StaticFiles
app.mount("/static", StaticFiles(directory="static"), name="static")
β’ Add a custom exception handler.
from fastapi import Request
from fastapi.responses import JSONResponse
class MyCustomException(Exception): pass
@app.exception_handler(MyCustomException)
async def custom_exception_handler(request: Request, exc: MyCustomException):
return JSONResponse(status_code=418, content={"message": "I'm a teapot"})
β’ Read a request header.
from fastapi import Header
@app.get("/headers/")
async def read_headers(user_agent: Optional[str] = Header(None)):
return {"User-Agent": user_agent}
β’ Get a raw
Request object.from fastapi import Request
@app.get("/request-info")
def get_request_info(request: Request):
return {"client_host": request.client.host}
#Python #FastAPI #API #WebDevelopment #Pydantic
βββββββββββββββ
By: @DataScience4 β¨