from django.shortcuts import get_object_or_404
from myapp.models import MyModel
def my_view(request, my_model_id):
my_model = get_object_or_404(MyModel, pk=my_model_id)
# Perform operations with my_model
- Import the
get_object_or_404
function from django.shortcuts
. - Import the
MyModel
model from myapp.models
. - Define a view function
my_view
that takes request
and my_model_id
as parameters. - Use
get_object_or_404
to retrieve an instance of MyModel
with the primary key (pk
) equal to my_model_id
. If no object is found, it raises a Http404
exception. - Perform operations using the retrieved
my_model
instance within the view function.
```