URL Parameters & Query Strings
URL parameters are captured from the URL path (e.g., /blog/42/). Query strings are key-value pairs after the ? (e.g., /search/?q=django). Both are essential for building dynamic, data-driven views.
15 min•By Priygop Team•Updated 2026
URL Parameters vs Query Strings
- URL params: /blog/<int:pk>/ — captured by path converters
- Query strings: /search/?q=django&page=2 — in request.GET
- URL params are mandatory — URL won't match without them
- Query strings are optional — use .get() with defaults
- URL params identify resources: /users/42/ = user with ID 42
- Query strings filter/modify: /users/?role=admin&sort=name
Parameters Example
Parameters Example
# blog/urls.py
# urlpatterns = [
# # URL parameters captured by path converters
# path('post/<int:pk>/', views.post_detail, name='detail'),
# path('category/<slug:slug>/', views.category, name='category'),
# path('archive/<int:year>/<int:month>/', views.archive, name='archive'),
# path('search/', views.search, name='search'),
# ]
# blog/views.py
# URL parameters — passed as function arguments
# def post_detail(request, pk):
# post = get_object_or_404(Post, pk=pk)
# return render(request, 'blog/detail.html', {'post': post})
# def archive(request, year, month):
# posts = Post.objects.filter(
# created_at__year=year,
# created_at__month=month
# )
# return render(request, 'blog/archive.html', {'posts': posts})
# Query strings — accessed via request.GET
# def search(request):
# query = request.GET.get('q', '')
# page = int(request.GET.get('page', 1))
# results = Post.objects.filter(title__icontains=query)
# return render(request, 'blog/search.html', {
# 'results': results, 'query': query
# })Tip
Tip
Use ForeignKey for many-to-one, ManyToManyField for many-to-many. Use a 'through' model when you need extra data on the relationship.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Forgetting related_name on ForeignKey. Without it, reverse lookups use 'modelname_set'. Set related_name='comments' for clarity.
Practice Task
Note
(1) Create Post and Comment models with ForeignKey. (2) Add a ManyToManyField for tags. (3) Test reverse lookups in the shell.
Quick Quiz
Key Takeaways
- URL parameters are captured from the URL path (e.
- URL params: /blog/<int:pk>/ — captured by path converters
- Query strings: /search/?q=django&page=2 — in request.GET
- URL params are mandatory — URL won't match without them