0
0
Djangoframework~30 mins

When async helps and when it does not in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
When async helps and when it does not in Django
📖 Scenario: You are building a Django web application that fetches data from an external API and also processes some local database queries.You want to understand when using asynchronous views can improve your app's performance and when it might not help.
🎯 Goal: Create a simple Django view that fetches data from an external API asynchronously and also performs a local database query synchronously.This will help you see when async helps (waiting for external API) and when it does not (database query blocking).
📋 What You'll Learn
Create a Django view function named fetch_data
Use the httpx library to fetch data asynchronously from https://jsonplaceholder.typicode.com/todos/1
Perform a synchronous query to get all objects from a model named Item
Return a JsonResponse combining the external API data and the count of Item objects
Use async def for the view and await the external API call
💡 Why This Matters
🌍 Real World
Many web apps fetch data from external services and query local databases. Knowing when async helps improves performance and user experience.
💼 Career
Understanding async in Django is important for backend developers to write efficient, scalable web applications.
Progress0 / 4 steps
1
Setup the Django model and import statements
Create a Django model named Item with a single field name as a CharField with max length 100. Also import JsonResponse from django.http and httpx at the top of your views.py file.
Django
Need a hint?

Define the Item model with one field name. Import JsonResponse and httpx at the top.

2
Add the async view function with external API URL
Create an async view function named fetch_data that sets a variable api_url to 'https://jsonplaceholder.typicode.com/todos/1'.
Django
Need a hint?

Define an async function fetch_data and set api_url to the given URL string.

3
Fetch external API data asynchronously and query local database synchronously
Inside the fetch_data function, use async with httpx.AsyncClient() as client to await client.get(api_url) and store the JSON response in external_data. Then query all Item objects synchronously with items = Item.objects.all().
Django
Need a hint?

Use async with and await to get the external API data. Then query Item.objects.all() synchronously.

4
Return combined JsonResponse with external data and item count
At the end of fetch_data, return a JsonResponse with a dictionary containing 'external' key set to external_data and 'item_count' key set to items.count().
Django
Need a hint?

Return a JsonResponse with keys 'external' and 'item_count' using the variables you created.