Skip to content

Commit

Permalink
Moved the text search to the queryset, keep the search GET parameter …
Browse files Browse the repository at this point in the history
…as the value of the search field after submitting.
  • Loading branch information
dhedegaard committed May 9, 2019
1 parent 57bab52 commit bac7336
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 20 deletions.
5 changes: 5 additions & 0 deletions youtube/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ class VideoQuerySet(models.QuerySet):
def exclude_deleted(self):
return self.exclude(deleted=True)

def text_search(self, search_query):
if search_query:
return self.filter(title__icontains=search_query)
return self

def create_or_update(self, channel, data):
'''
Creates or updates a `Video` object with the data given, for the
Expand Down
2 changes: 1 addition & 1 deletion youtube/templates/youtube/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
<div class="navbar-right">
<form class="navbar-form navbar-left">
<div class="input-group">
<input name="q" type="search" class="form-control" placeholder="Search..." />
<input name="q" type="search" class="form-control" placeholder="Search..." value="{{ request.GET.q|default:'' }}" />
<span class="input-group-btn">
<button type="submit" class="btn btn-default" type="button">
<span class="glyphicon glyphicon-search" aria-hidden="true" />
Expand Down
30 changes: 11 additions & 19 deletions youtube/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,13 @@


def index(request):
videos = (
Video.objects.
filter(uploader__hidden=False).
exclude_deleted().
prefetch_related('uploader'))

# Text search.
q = request.GET.get('q', '')
if q:
videos = videos.filter(title__icontains=q)

return render(request, 'youtube/index.html', {
'videos': videos,
'videos': (
Video.objects.
filter(uploader__hidden=False).
exclude_deleted().
text_search(request.GET.get('q', '')).
prefetch_related('uploader')),
'full_url': request.build_absolute_uri(request.get_full_path()),
})

Expand All @@ -41,16 +35,14 @@ def channel(request, author):
# Fetch the channel, or 404.
channel = get_object_or_404(qs.filter(
Q(Q(author=author) | Q(channelid=author))))
videos = channel.videos.exclude_deleted()

# Text search.
q = request.GET.get('q', '')
if q:
videos = videos.filter(title__icontains=q)

# Render and return.
return render(request, 'youtube/index.html', {
'videos': videos,
'videos': (
channel.videos.
exclude_deleted().
text_search(request.GET.get('q', ''))
),
'channel': channel,
'full_url': request.build_absolute_uri(request.get_full_path()),
})
Expand Down

0 comments on commit bac7336

Please sign in to comment.