Question bank
Pick an answer to see if you're right — with an explanation.
All topicsPythonSQL / MySQLData ScienceNumPyPandasMatplotlibMachine LearningDeep LearningArtificial IntelligenceLarge Language ModelsDjangoAPIsGit & GitHubPower BIExcelStatistics
DjangoMedium
Why should `success_url` on a class-based view use `reverse_lazy`?
areverse() is deprecated
bIt caches the URL for faster redirects
cIt works with POST only
dThe URLconf isn't loaded when the class attribute is evaluated at import time
Explanation: reverse_lazy defers resolution until the value is actually used.
DjangoHard
How many database queries does this run?
qs = Post.objects.filter(published=True)
qs = qs.order_by('-created')
for p in qs[:5]:
print(p.title)
aOne, when the loop starts iterating
bTwo, one per queryset line
cThree
dSix, one per post plus one
Explanation: Querysets are lazy: filtering and slicing only build the SQL, which is sent once when the results are first needed.
DjangoHard
How many queries does this loop run for 50 orders (no other optimisation)?
for o in Order.objects.all():
print(len(o.items.all()))
a1
b2
c51
d100
Explanation: One query for the orders plus one per order for its items — the N+1 problem; `prefetch_related('items')` makes it 2.
DjangoHard
When should a project switch to a custom user model?
aOnly after real users exist in the database
bAt the start, before the first migration, by setting AUTH_USER_MODEL
cNever; Django forbids it
dAny time, it is a one-line change with no data impact
Explanation: Swapping the user model after migrations have run is painful, so define it and point AUTH_USER_MODEL at it before the first migrate.
DjangoHard
Which statement decrements stock safely even if two requests run at the same moment?
ap.stock = p.stock - 1; p.save()
bProduct.objects.filter(pk=p.pk).update(stock=F('stock') - 1)
cp.refresh_from_db(); p.stock -= 1; p.save()
dProduct.objects.get(pk=p.pk).stock -= 1
Explanation: F() makes the database compute `stock - 1` in a single UPDATE, avoiding a read-modify-write race.