Bird
0
0

How would you write an async function to fetch usernames of all active users using Django's async ORM?

hard📝 Application Q8 of 15
Django - Async Django
How would you write an async function to fetch usernames of all active users using Django's async ORM?
Aasync def get_usernames(): users = User.objects.filter(active=True).values_list('username', flat=True) return users
Basync def get_usernames(): users = await User.objects.filter(active=True).values_list('username', flat=True).all() return users
Casync def get_usernames(): users = await User.objects.filter(active=True).values_list('username', flat=True).aall() return users
Dasync def get_usernames(): users = await User.objects.afilter(active=True).values_list('username', flat=True) return list(users)
Step-by-Step Solution
Solution:
  1. Step 1: Use async ORM to filter and get values

    Use 'await' with QuerySet methods; 'values_list' returns QuerySet of usernames.
  2. Step 2: Convert QuerySet to list

    Awaiting the async QuerySet returns a list of usernames directly.
  3. Final Answer:

    Use 'await' with afilter and values_list, then convert to list -> Option D
  4. Quick Check:

    Async afilter + values_list + await + list() = async def get_usernames(): users = await User.objects.afilter(active=True).values_list('username', flat=True) return list(users) [OK]
Quick Trick: Await QuerySet, then convert to list for results [OK]
Common Mistakes:
MISTAKES
  • Not awaiting the QuerySet
  • Using non-existent 'aall()' method
  • Awaiting 'all()' instead of QuerySet

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes