Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Category Filtering and Keyword Search

Category Filtering and Keyword Search

In this chapter you will learn to handle URL query parameters, implementing category filter navigation and keyword search functionality.


URL query parameter

Query parameters are the part of a URL after the question mark, such as /?category=django&q=入门。

In a Django view function, use request.GET to get these parameters.

Example

def

index

(

request

)

:

   

request.GET is a dictionary-like object

   

.get('key', 'default value') safely gets a parameter, returning the default value if it does not exist

    category_slug

=

request.

GET

.

get

(

'category'

,

''

)

 

Category filtering

   

keyword

=

request.

GET

.

get

(

'q'

,

''

)

               

Search keyword

   

print

(

f

'Category: {category_slug}, Search: {keyword}'

)


ORM chained filtering and Q objects

Filtering and searching require dynamically concatenating query conditions.

Example

File path: blog/views.py update the index function

from

django.

shortcuts

import

render

from

django.

db

.

models

import

Q          

Q objects are used to combine complex query conditions

from

.

models

import

Post

,

Category

def

index

(

request

)

:

   

"""Blog homepage: display the article list, supporting category filtering + keyword search"""

    posts

=

Post.

objects

.

all

(

)

.

order_by

(

'-created_at'

)

   

1. Get query parameters

    category_slug

=

request.

GET

.

get

(

'category'

,

''

)

   

keyword

=

request.

GET

.

get

(

'q'

,

''

)

   

2. Filter by category

   

if

category_slug:

       

category__slug: access the slug field of the category table via a foreign key (double underscore)

        posts

=

posts.

filter

(

category__slug

=

category_slug

)

   

3. Search by keyword (title or summary)

   

if

keyword

:

       

Q(title__icontains=...) | Q(summary__icontains=...): OR combination

       

icontains: case-insensitive contains query

        posts

=

posts.

filter

(

            Q

(

title__icontains

=

keyword

)

| Q

(

summary__icontains

=

keyword

)

       

)

   

4. Get all categories (for rendering the filter navigation)

    categories

=

Category.

objects

.

all

(

)

    context

=

{

       

'posts'

: posts

,

       

'categories'

: categories

,

       

'category_slug'

: category_slug

,

 

Pass to the template to highlight the current selection

       

'keyword'

:

keyword

,

             

Echo the search keyword

       

'title'

:

'RUNOOB Blog - Home'

,

   

}

   

return

render

(

request

,

'blog/index.html'

,

context

)

ORM query method descriptions

Method Meaning Example
field__exact Exact match title__exact='Django'
field__iexact Case-insensitive exact match title__iexact='django'
field__contains Contains (case-sensitive) title__contains='入门'
field__icontains Contains (case-insensitive) title__icontains='django'
field__gte / lte Greater than or equal / less than or equal created_at__gte='2024-01-01'
field__in=[...] In a list category__in=[1, 2, 3]

Double underscore __ is a core convention of Django ORM: used to access fields of related models, or to specify the query method of a field. For example category__slug represents crossing a foreign key to the slug field of the Category table.


Update the homepage template

Add category filter navigation and a search box above the article list.

Example

{% extends 'blog/base.html' %}

{% block title %}{{ title }}{% endblock %}

{% block content %}

Latest Articles

    Total {{ posts.count }} posts

    {% if keyword %}, search "{{ keyword }}"{% endif %}

{% if posts %}

   

        {% for post in posts %}

       

           

               

                   

{{ post.category.name }}

                   

{{ post.title }}

                   

{{ post.summary|truncatechars:80 }}

                   

{{ post.created_at|date:"Y-m-d" }}

               

           

       

        {% endfor %}

   

{% else %}

   

No matching articles found

{% endif %}

{% endblock %}

Filter navigation and search box styles

Example

/* append to the style in base.html */

.search-bar

{

   

margin-bottom

:

20px

;

}

.search-input

{

   

width

:

100%

;

   

padding

:

12px

16px

;

   

border

:

2px

solid

#eee

;

   

border-radius

:

8px

;

   

font-size

:

15px

;

   

outline

:

none

;

    transition

:

border-color

0.2s

;

}

.search-input

:focus

{

   

border-color

:

#2c3e50

;

}

.clear-btn

{

   

position

:

absolute

;

   

right

:

12px

;

   

top

:

50%

;

    transform

:

translateY

(

-50%

)

;

   

color

:

#999

;

   

text-decoration

:

none

;

   

font-size

:

18px

;

}

.category-bar

{

   

display

:

flex

;

    gap

:

10px

;

   

margin-bottom

:

16px

;

   

flex-wrap

:

wrap

;

}

.category-bar

a

{

   

padding

:

6px

16px

;

   

border

:

1px

solid

#ddd

;

   

border-radius

:

20px

;

   

text-decoration

:

none

;

   

color

:

#333

;

   

font-size

:

14px

;

    transition

:

all 0.2s

;

}

.category-bar

a

.active

{

   

background

:

#2c3e50

;

   

color

:

#fff

;

   

border-color

:

#2c3e50

;

}

.category-bar

a

:hover

{

   

border-color

:

#2c3e50

;

}

.result-info

{

   

color

:

#999

;

   

font-size

:

14px

;

   

margin-bottom

:

16px

;

}

.card-link

{

   

text-decoration

:

none

;

   

color

:

inherit

;

}

The category button links also preserve category and keyword Parameters:?category={{ cat.slug }}&q={{ keyword }}. In this way, after users search first and then click a category, the search conditions are not lost, and both conditions take effect at the same time.


Hands-on: Test filtering and search

Start the server and verify the following:


Chapter Summary

In this chapter you mastered handling URL query parameters in Django: request.GET.get() to get parameters, ORM chained filtering + Q objects for complex queries, and dynamically concatenating URL parameters in templates for filter links.

Category filtering and search let users quickly find articles of interest.