🐍📰 Django Migrations: A Primer In this tutorial, you’ll get comfortable with Django migrations and learn how to create database tables without writing any SQL, how to automatically modify your database after you changed your models, and more. #python
Django Migrations Primer
More Relevant Posts
-
🚀 Django's ORM (Object-Relational Mapper) (Python) Django's ORM provides an abstraction layer for interacting with databases. It allows you to perform database operations using Python code instead of writing SQL. The ORM translates Python code into SQL queries, making it easier to work with different database backends (like PostgreSQL, MySQL, and SQLite). Using the ORM improves code readability, reduces the risk of SQL injection vulnerabilities, and simplifies database management. #Python #PythonDev #DataScience #WebDev #professional #career #development
To view or add a comment, sign in
-
-
---- Slow Requests in Python (Django): What’s Really the Problem? Slow APIs are not a Python issue , they’re an engineering failure. Most slow requests come from poor decisions in data access, logic, and system design, not the language itself. * Too many database queries (N+1 problem): This happens when the app queries the database inside loops instead of fetching related data efficiently. What should be one query turns into dozens or hundreds, killing performance and scalability. * Inefficient ORM usage: Fetching full objects when only a few fields are needed adds unnecessary weight to your queries. This increases memory usage and slows down both processing and serialization. * Blocking synchronous code: Long operations like external API calls, file handling, or heavy computations block the request cycle. Since Django runs synchronously by default, everything waits and your response time explodes. * No caching strategy: If your app keeps recalculating the same results or hitting the database for identical requests, you’re wasting resources. Caching avoids redundant work and drastically improves speed. * Heavy serialization: Returning large or deeply nested data structures makes responses slower. Overloaded serializers and missing pagination can turn even simple endpoints into performance bottlenecks. -> In conclusion : When you are in development phase, always think as if you are already in production. Your users are not 1 or 2 they can be thousands or even millions.
To view or add a comment, sign in
-
-
🚀 Understanding Django ORM — The Bridge Between Databases and Python If you're getting started with Django, one of the most powerful features you'll come across is the ORM (Object-Relational Mapping). 🔹 What is ORM? ORM allows you to interact with your database using Python code instead of writing raw SQL queries. It acts as a translator between your database and your application. 🔹 Why use Django ORM? ✔ Write clean, readable Python instead of complex SQL ✔ Faster development with less boilerplate ✔ Built-in protection against SQL injection ✔ Database-agnostic (PostgreSQL, MySQL, SQLite, etc.) 🔹 How it works (as shown in the image): You write Python code using Django models Django ORM converts it into SQL queries The database executes those queries Results are returned as Python objects 🔹 Basic CRUD Operations in Django ORM: 🟢 Create Student.objects.create(name="Ali", age=21) 🔵 Read Student.objects.all() Student.objects.filter(age__gt=20) 🟡 Update student = Student.objects.get(id=1) student.age = 22 student.save() 🔴 Delete student = Student.objects.get(id=1) student.delete() 🔹 Example Comparison: SQL: SELECT * FROM students WHERE age > 20; Django ORM: Student.objects.filter(age__gt=20) 🔥 Powerful Query (Combining Filters, Ordering, and Aggregation): Student.objects.filter(age__gt=20).exclude(name="Ali").order_by("-age") 💡 Final Thought: Django ORM lets developers focus more on application logic rather than database complexity, making development faster, cleaner, and more scalable. #Django #Python #WebDevelopment #ORM #BackendDevelopment #SoftwareEngineering #CRUD
To view or add a comment, sign in
-
-
🧠 What is a Descriptor in Python ? A descriptor is any object that defines one or more of these methods: __get__() → Access attribute __set__() → Set attribute __delete__() → Delete attribute 👉 In simple terms: Descriptors control how attributes behave in a class Why It Matters? Whenever you use: @property 👉 You’re already using descriptors under the hood. Yes — even Django models rely heavily on descriptors. Example: class Descriptor: def __get__(self, instance, owner): print("Getting value") return instance._value def __set__(self, instance, value): print("Setting value") instance._value = value class MyClass: attr = Descriptor() obj = MyClass() obj.attr = 10 # calls __set__ print(obj.attr) # calls __get__ What’s Happening Internally? When you do: obj.attr Python does NOT directly fetch the value. 👉 It checks: Does attr have __get__? If yes → call descriptor logic Real-World Use Cases Descriptors are used in: ✅ @property (getter/setter logic) ✅ Django ORM fields (models.CharField) ✅ Data validation frameworks ✅ Lazy loading attributes ✅ Caching values Example (Validation): class PositiveNumber: def __set__(self, instance, value): if value < 0: raise ValueError("Must be positive") instance.__dict__['value'] = value def __get__(self, instance, owner): return instance.__dict__.get('value', 0) class Product: price = PositiveNumber() p = Product() p.price = 100 # ✅ p.price = -10 # ❌ Error 👉 Clean validation without cluttering your class. Have you ever used descriptors directly, or only via @property? #Python #AdvancedPython #OOP #Django #SoftwareEngineering #BackendDevelopment #infosys #citi #SoftwareDevelopment
To view or add a comment, sign in
-
My Python loop processed 5 reports in 2.5 seconds. After adding one decorator: 0.54 seconds. I changed zero call sites. Here's how it works. A function that's slow because it does real work — database queries, aggregations — gets decorated with @app.direct_task. That's it. The caller doesn't change. Exception handling doesn't change. The return type doesn't change. In development: set one environment variable and the decorator is invisible - tests pass, the function runs inline as it always did. In production: start a worker. The same call now routes to a distributed runner. The caller still blocks and gets the value back directly. No .result. No futures. No refactoring. For parallelism without touching the call site at all: add parallel_func to the decorator with a small helper that describes how to split the input. Pynenc dispatches one task per chunk, collects results, and returns the same type the caller expected. Full write-up + runnable demo (no Docker, no Redis, runs in ~30 seconds): https://lnkd.in/eySD7h_H What's the slowest loop in your codebase right now? #python #backend #distributedsystems #opensource
To view or add a comment, sign in
-
Postgres 18 makes generated columns virtual by default. Paolo Melchiorre, Python developer & Django contributor, explores what this means using concrete examples at POSETTE: An Event for Postgres 2026 Paolo walks through examples showing how generated columns evolved across PostgreSQL versions & what problems they solve well. The talk uses Django as a case study for how generated columns are exposed & used in production through a widely adopted Python framework: 🔹 How generated columns behave differently across PostgreSQL versions 🔹 New trade-offs around performance, storage & query behavior 🔹 How ORM abstractions influence the adoption of database features in production 🔹 Recent Django 6.0 improvements that better align with PostgreSQL's generated column behavior Mark your calendar for POSETTE Livestream 2 on Wed 17 Jun https://lnkd.in/gZzv6j7C #PosetteConf
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟲𝟰: 𝗛𝗼𝘄 𝗣𝘆𝘁𝗵𝗼𝗻 𝗖𝗹𝗮𝘀𝘀𝗲𝘀 𝗕𝗲𝗰𝗼𝗺𝗲 𝗗𝗷𝗮𝗻𝗴𝗼 𝗠𝗼𝗱𝗲𝗹𝘀 Today I linked two big ideas. Python object oriented programming. And Django models. They are the same thing. A Django model is just a Python class. Here is what I learned about Python classes. A class is a blueprint. An object is a built thing from that blueprint. - class Car: defines the blueprint. - __init__ runs when you build the object. self points to that new object. - Instance attributes like self.brand are unique to each object. - Class attributes like company are shared by all objects. Methods live inside classes. - Instance method: uses self. Works with your object's data. - Class method: uses cls. Decorated with @classmethod. Works with the class itself. - Static method: uses no self or cls. Decorated with @staticmethod. Just a function inside the class. Inheritance lets a child class reuse a parent class. - class Dog(Animal): Dog gets all of Animal's code. - Use super() to run the parent's __init__. Python does not have private. It has conventions. - _name is protected. A hint to other coders. - __name is private. Python changes its name to _ClassName__name. Dunder methods define how your object acts with Python's built-ins. - __str__: for print() and str(). - __len__: for len(). - __eq__: for ==. Abstract Base Classes force subclasses to write specific methods. - from abc import ABC, abstractmethod - @abstractmethod means "you must write this method". Now for Django. A Django model is a Python class that inherits from models.Model. - Each class attribute becomes a database column. - Django reads these attributes and creates the SQL table for you. You do not write SQL. You run two commands. - python manage.py makemigrations - python manage.py migrate The __str__ method in your model controls what you see in the Django admin. Without it you see "Post object (1)". With it you see your post title. OOP is the foundation. Django models are the practical application. A model class maps directly to a database table. Fields map to columns. Your __str__ method controls the display. Understanding Python classes first makes Django models obvious. Source: https://lnkd.in/gChPWWZS
To view or add a comment, sign in
-
🔥 Mastering JSON Parsing in Python! 🐍 Ever wondered how to work with JSON in Python? JSON (JavaScript Object Notation) is a popular format for data exchange due to its simplicity and readability. For developers, understanding JSON parsing is essential as it allows you to interact with APIs, handle configuration files, and exchange data between different systems effortlessly. Here are the steps to parse JSON in Python: 1️⃣ Load the JSON data using the `json.loads()` function. 2️⃣ Access the values using keys just like a Python dictionary. 3️⃣ Iterate through JSON arrays to extract multiple values. 👉 Pro Tip: Use `json.dumps()` to convert Python objects back to JSON. ❌ Common Mistake: Forgetting to handle exceptions when parsing JSON can lead to runtime errors. 🚀 Ready to level up your Python skills? Try parsing JSON with this code snippet: ``` import json # Sample JSON data json_data = '{"name": "John", "age": 30, "city": "New York"}' # Parse JSON data = json.loads(json_data) # Access values name = data['name'] age = data['age'] city = data['city'] print(name, age, city) ``` 🤔 What's your favorite way to work with JSON data in Python? 🌐 View my full portfolio and more dev resources at tharindunipun.lk #JSON #Python #APIs #DataExchange #CodingTips #JSONParsing #Programming #DeveloperCommunity #TechSkills
To view or add a comment, sign in
-
-
Everyone told me I was doing it wrong. "Just pip install it." "Use FastAPI, use Redis — that's how real projects work." I ignored all of it. Over the past few months, I built 46 Python applications using nothing but the standard library. Zero external dependencies. Pure Python + SQLite. I wrote about what I learned — the unexpected benefits, the real costs, and why constraints can be a solo developer's best friend. https://lnkd.in/dYG_rXpa
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development