你能在 Django 中将参数传递给 ListView 吗?

Can you pass an argument to ListView in Django?

我正在使用 Django 创建一个 Fixture webapp。我在下面写了 class,它显示了一线队的赛程列表。我可以将其重写为 TeamView,然后传递 team_id?

class FirstView(generic.ListView):
    template_name = 'fixtureapp/team.html'
    context_object_name = 'fixtures'

def get_queryset(self):
    """return all first team matches"""
    return Match.objects.filter(team_id=1).order_by('date')

def get_context_data(self, **kwargs):
    data = super().get_context_data(**kwargs)
    data['page_title'] = '1st Team Fixtures'
    return data

我有以下网址,我该如何重写这些以匹配?

urlpatterns = [
    path('', views.HomeView.as_view(), name='home'),
    path('first', views.FirstView.as_view(), name='first'),
    path('second', views.SecondView.as_view(), name='second'),

如您所见,我目前创建了第二个 class,称为 SecondView,这几乎是 FirstView 的副本,不是很干

我可以简要介绍一下它是如何工作的,您可以应用其余的逻辑。基本思路是使用 slug.

在您的 html 中,您可以使用 url:

为 slug 命名
<a href="{% url 'team_by_id' teamid.slug %}"></a>

在 urls.py 中,得到那个 slug :

path('team/<slug:teamid_slug>/', views.TeamView.as_view(), name='team_by_id'),

您的视图应根据此 slug 过滤查询,如果没有给定 slug 它将提供所有匹配记录。您可以应用一些其他适合您的逻辑。

class TeamView(generic.ListView):
    queryset = Match.objects.all().order_by('date')
    template_name = 'fixtureapp/team.html'
    context_object_name = 'fixtures'

def get_queryset(self):
    """return all team_id team matches"""
    return Match.objects.filter(team_id__slug=self.kwargs.get('teamid_slug')).order_by('date')

另请查看 Dynamic Filtering

的文档