擅长:python、mysql、java
<p>首先,将<code>'anythinghereworks'</code>重命名为更有用的名称,并重命名<code>DetailView</code>以避免与Django的<code>DetailView</code>冲突。例如:</p>
<pre><code>path('<cat_slug>/<slug>', views.MyDetailView.as_view(), name='detail_name')
</code></pre>
<p>然后您可以覆盖<code>get_object</code>以在<code>slug</code>和<code>cat_slug</code>上进行筛选</p>
<pre><code>class MyDetailView(DetailView):
def get_object(self):
return Detail.objects.get(slug=self.kwargs['slug'], categorie__slug='self.kwargs['cat_slug'])
</code></pre>
<p>或者您可以覆盖<code>get_queryset</code>并在那里过滤分类。这里不需要过滤<code>slug=self.kwargs['slug']</code>,因为Django将在<code>get_object</code>方法中处理它</p>
<pre><code>class MyDetailView(DetailView):
def get_queryset(self):
queryset = super().get_queryset()
queryset = queryset.filter(categorie__slug=self.kwargs['cat_slug'])
return queryset
</code></pre>
<p>在这两种情况下都可以删除<code>slug_field = 'slug'</code>,因为<code>'slug'</code>是默认值。在第一种情况下,Django将使用<code>get_object</code>方法,因此根本不使用<code>slug_field</code></p>