Posts

Mastering Django ORM Update Queries — From Basics to Pro Level

Updating data properly is just as important as selecting data. In this guide, you will learn how to update records correctly in Django ORM — from basic .save() usage to pro techniques like atomic updates, bulk updates, F expressions, and best practices! 📚 1. Basic Update Using .save() Fetch and modify a single object user = NewUser.objects.get(pk=1) user.email = 'newemail@example.com' user.save() ⚡ 2. Updating Specific Fields with .save(update_fields=[...]) user = NewUser.objects.get(pk=1) user.email = 'newemail@example.com' user.save(update_fields=['email']) 🎯 3. Updating Multiple Records at Once Using .update() NewUser.objects.filter(user_type=2).update(is_active=False) 🧠 4. .save() vs .update() — Key Differences Aspect .save() .update() Works on Single object QuerySet (multiple) Triggers signals? ✅ Yes ❌ No Auto-updates auto_now fields? ✅ Yes ❌ No Custom logic inside save() runs? ✅ Yes ❌ No Speed for bulk ❌ Slow ✅ Fast 🔥 5. Upda...

Mastering Django ORM Select Queries (Ultimate Guide)

# Recreating the final HTML file content final_html_content = """ Complete Guide to Django ORM Select Queries Complete Guide to Django ORM Select Queries — From Basics to Pro Level Selecting data efficiently is one of the most important skills for Django developers. In this ultimate guide, we'll cover everything — from basic selecting, filtering, ordering, to deep ORM tricks like only() , defer() , select_related() , prefetch_related() , and even professional safe querying patterns! 📚 1. Basic Data Selection Select all records qs = NewUser.objects.all() Select specific fields using .values() qs = NewUser.objects.values('email') Select field values as list using .values_list() qs = NewUser.objects.values_list('email', flat=True) 🎯 2. Filtering While Selecting Filter records before selecting qs = NewUser.objects.filter(user_type=2, is_active=True).values('email') Use .first() for Safe Single Record email = NewUser.objec...

A Complete Tutorial: Using RabbitMQ + Celery with Multiple Django Projects

In this post, we’ll walk through how to set up RabbitMQ on one server and run Celery across multiple Django projects, with clean project isolation, scalable architecture, and best practices. ✅ Step 1: Install RabbitMQ (Server A) ➡️ On Ubuntu (Server A): sudo apt update sudo apt install rabbitmq-server -y sudo systemctl enable rabbitmq-server sudo systemctl start rabbitmq-server ➡️ Enable RabbitMQ Management UI: sudo rabbitmq-plugins enable rabbitmq_management Visit: http://server-a-ip:15672 (default guest/guest). ➡️ Create RabbitMQ User: sudo rabbitmqctl add_user admin strongpasswordhere sudo rabbitmqctl set_user_tags admin administrator sudo rabbitmqctl set_permissions -p / admin ".*" ".*" ".*" sudo rabbitmqctl delete_user guest # For security ➡️ Open Ports: 5672 (for Celery workers) 15672 (for admin UI, restricted IPs recommended) ✅ Step 2: Project Structure (Multiple Django Projects Example) /var/www/ ├── project_...

How to Install and Manage PostGIS with a Non-Superuser Role

Image
Prerequisite: PostgreSQL Version This guide assumes you are using PostgreSQL version 14 or later, which supports the necessary commands for PostGIS installation and management. Ensure your PostgreSQL server is up-to-date before proceeding. This guide ensures that PostGIS is installed and configured properly for a specific user, such as administrator , while avoiding common issues. 1. Ensure Superuser Access sudo -i -u postgres psql --dbname=financethat 2. Create a Role for PostGIS Management CREATE ROLE administrator WITH LOGIN PASSWORD 'your_secure_password'; GRANT ALL PRIVILEGES ON DATABASE financethat TO administrator; 3. Install PostGIS To install PostGIS on Ubuntu, first ensure you have the required PostgreSQL version installed. Then, use the following commands: sudo apt update sudo apt install postgis postgresql-14-postgis-3 Replace 14 with your PostgreSQL version if different. After installation, enable PostGIS in...

Implementing Throttling in Django REST Framework.

Implementing Throttling in Django REST Framework to Manage High Traffic and Prevent Abuse Introduction In high-traffic applications, it’s essential to protect server resources and ensure fair usage among users. Throttling is a method used in Django REST Framework (DRF) to limit the rate of requests, helping prevent abuse and manage load. In this article, we’ll explore how to implement throttling in DRF, including ways to apply it to specific views and dynamically whitelist IPs. What is Throttling? Throttling controls the rate of requests an API endpoint can receive from a single client. It’s a valuable tool for: Preventing abuse by limiting request rates for each user or IP address. Managing server load by avoiding high request volumes that can overwhelm the application. In Django REST Framework, throttling is easy to configure with built-in classes like UserRateThrottl...

Leveraging Asynchronous Views in Django REST Framework for High-Performance APIs

As web applications grow, handling a high volume of concurrent requests becomes essential. Traditional Django views, which are synchronous, can slow down the system by tying up resources for each request. Fortunately, starting with Django 3.1, asynchronous views were introduced. By leveraging async views, Django can serve more requests concurrently, improving scalability and responsiveness. Understanding Asynchronous Views in Django Asynchronous views allow Django to handle tasks that involve waiting, like database queries or API calls, without blocking threads. This approach allows the server to handle additional requests in the meantime. In Django, async views use the async and await keywords to enable non-blocking behavior. Example: Fetching Data from an External API Here’s an example of an asynchronous view in Django that fetches weather data from an external API. Instead of blocking while waiting for the API response, Django can handle oth...

Differences Between List, Dictionary, and Tuple in Python

In Python, lists, dictionaries, and tuples are all built-in data structures that store collections of items. While they share similarities, each has its distinct characteristics and use cases. This post provides a comprehensive comparison. Comparison Table Aspect List Dictionary Tuple Definition An ordered collection of elements. A collection of key-value pairs. An ordered and immutable collection of elements. Access Method Index-based access ( my_list[0] ). Key-based access ( my_dict['key'] ). Index-based access ( my_tuple[0] ). Mutability Mutable: Elements can be added, removed, or changed. Mutable (for values): Keys/values can be added, modified, or removed, but keys must be immutable. Immutable: Elements cannot be changed once assigned. Order Guarantee Maintains th...