首页 > 解决方案 > 在 DetailView 中使用对象

问题描述

假设我有一个名为 City 的模型,它有一个 name 属性。在我的 DetailView 中,我想使用单击它的特定城市的名称来发出一些 api 请求,然后将其发送到 detailview.html。

有没有办法访问它?

标签: pythondjangocruddjango-class-based-viewsdetailview

解决方案


如果 的nameCity唯一,是的。例如,您可以创建一个 URL:

from django.urls import path
from app_name.views import CityDetailView

urlpatterns = [
    path('city/<str:name>/', CityDetailView.as_view(), name='city-detail'),
]

然后你可以做一个DetailView

from django.shortcuts import get_object_or_404
from django.views.generic.detail import DetailView
from app_name.models import City

class CityDetailView(DetailView):
    model = City
    template_name = 'name_of_template.html'

    def get_object(self, *args, **kwargs):
        return get_object_or_404(City, name=self.kwargs['name'])

在模板中,例如列出城市的模板,您可以生成一个 URL:

<a href="{% url 'city-detail' 'Bucharest' %}">Bucharest</a>

然而,通常使用名称,而是使用slug [Django-doc]。蛞蝓通常在视觉上更令人愉悦,因为它避免了百分比编码数据。通常,您还会在 slug 字段上添加数据库索引。此外,aDetailView会查看 url 是否有一个名为 slug 的参数,然后会自动尝试过滤模型中名为 slug 的字段。


推荐阅读