0
0
Djangoframework~10 mins

When async helps and when it does not in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define an async view in Django.

Django
from django.http import JsonResponse

async def my_view(request):
    data = await fetch_data()
    return JsonResponse({"result": data})

# The key word to define this view is [1]
Drag options to blanks, or click blank then click option'
Adef
Basync
Cawait
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'def' instead of 'async def' for async views.
2fill in blank
medium

Complete the code to await an asynchronous database call in Django.

Django
async def get_user(request):
    user = await User.objects.aget(id=1)
    return JsonResponse({"username": user.username})

# The method to asynchronously get a user is [1]
Drag options to blanks, or click blank then click option'
Aget
Bcreate
Cfilter
Daget
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'get' which is synchronous and blocks the event loop.
3fill in blank
hard

Fix the error in the async view that tries to use a synchronous ORM call.

Django
async def list_items(request):
    items = [1]
    return JsonResponse({"count": len(items)})
Drag options to blanks, or click blank then click option'
Aawait Item.objects.aall()
BItem.objects.all()
Cawait Item.objects.all()
DItem.objects.aall()
Attempts:
3 left
💡 Hint
Common Mistakes
Calling synchronous 'all()' inside async function without await.
4fill in blank
hard

Fill both blanks to create an async view that fetches data and returns JSON.

Django
async def data_view(request):
    data = await [1].objects.[2]()
    return JsonResponse({"data": list(data)})
Drag options to blanks, or click blank then click option'
AProduct
Baall
Call
DUser
Attempts:
3 left
💡 Hint
Common Mistakes
Using synchronous 'all()' in async views.
5fill in blank
hard

Fill all three blanks to create an async view that filters users and returns their names.

Django
async def active_users(request):
    users = await [1].objects.[2](is_active=True).[3]()
    return JsonResponse({"users": [user.username for user in users]})
Drag options to blanks, or click blank then click option'
AUser
Bfilter
Caall
Dget
Attempts:
3 left
💡 Hint
Common Mistakes
Using synchronous methods in async views.