📜  get_object_or_404 django - Python (1)

📅  最后修改于: 2023-12-03 15:15:15.104000             🧑  作者: Mango

Get_object_or_404 Django - Python

The get_object_or_404 function in Django is a convenient shortcut to retrieve a single object from the database based on its primary key or unique slug. If the object does not exist, a 404 error page is raised, which is a built-in Django view that displays a page not found error in the browser.

To use get_object_or_404, you will need to have a model defined in your Django project, which is a representation of a database table. In the example below, we'll use a simple model for a blog post.

# models.py

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    published = models.BooleanField(default=False)
    slug = models.SlugField()

    def __str__(self):
        return self.title

Once you have your model defined, you can use get_object_or_404 in your views to retrieve an instance of the model based on its primary key or slug. Here's an example view that shows how to use get_object_or_404 to retrieve a blog post by its slug:

# views.py

from django.shortcuts import get_object_or_404, render
from .models import Post

def post_detail(request, slug):
    post = get_object_or_404(Post, slug=slug)
    return render(request, 'post_detail.html', {'post': post})

In this view, we're using get_object_or_404 to retrieve a Post object based on its slug field. If the object does not exist, get_object_or_404 raises a Http404 exception, which is handled by Django to display a page not found error.

To use get_object_or_404 in your own project, you'll need to import it from the django.shortcuts module, which is part of the built-in Django shortcuts. You can then use it in your views to retrieve models from the database based on their primary key or other unique fields.

Overall, get_object_or_404 is a powerful and convenient function that makes it easy to retrieve objects from the database in Django. By using this function in your views, you can avoid writing boilerplate code to handle missing objects, and provide your users with a clean error message when an object cannot be found.