Tuesday, November 19, 2024
Google search engine
HomeLanguagesDjango shortcuts: get_list_or_404()

Django shortcuts: get_list_or_404()

Some functions are hard as well as boring to code each and every time. But Django users don’t have to worry about that because Django has some awesome built in functions to make our work easy and enjoyable. Let’s discuss get_list_or_404() here.

get_list_or_404()

This function calls given model and get list from that if that list or model doesn’t exist it raise 404 error.

Example:

Suppose we want to fetch articles from model then we can use:

# import get_list_or_404()
from django.shortcuts import get_list_or_404


# defining view
def article_view(request):

    # retrieving article from model
    articles = get_list_or_404(Articles)

This is the advantage of Django, if you hardcode that then you have to write this much line of code:

# import Http404
from django.http import Http404

# defining view
def article_view(request):

# try except logic
try:
 articles = Articles.objects.all()

except Articles.DoesNotExist:
 raise Http404("Given query not found....")
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments