Skip to content

Commit

Permalink
endpoint with prefetch added
Browse files Browse the repository at this point in the history
  • Loading branch information
gslopez committed Feb 5, 2024
1 parent f863150 commit 0aca81b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
1 change: 1 addition & 0 deletions boards/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

urlpatterns = [
path('', views.all),
path('prefetch', views.all_prefetch),
path('first', views.first),
path('last', views.last),
]
23 changes: 22 additions & 1 deletion boards/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from django.http import JsonResponse
from boards.models import Board
from django.db.models import Prefetch

def all(request):
response = {}
boards = Board.objects.all()

for board in list(Board.objects.all()):
for board in list(boards):
response[board.id] = {
"id": board.id,
"name": board.name,
Expand All @@ -18,6 +20,25 @@ def all(request):

return JsonResponse(response)

def all_prefetch(request):
response = {}
# Look at this "prefetch_related" stuff, that's all!
boards = Board.objects.prefetch_related(Prefetch('reports', to_attr='reports_list'))

for board in list(boards):
response[board.id] = {
"id": board.id,
"name": board.name,
"reports": [],
}
for report in board.reports_list:
response[board.id]["reports"].append({
"id": report.id,
"name": report.name
})

return JsonResponse(response)

def first(request):
board = Board.objects.first()
response = {
Expand Down
1 change: 1 addition & 0 deletions myproject/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
# Application definition

INSTALLED_APPS = [
'django_extensions',
'boards',
'django.contrib.admin',
'django.contrib.auth',
Expand Down

0 comments on commit 0aca81b

Please sign in to comment.