通过 URL kwargs 实现多个路径的单一视图

问题描述 投票:0回答:1

我正在构建一个简单的 API,列出各种植物。目前,它仅限于通过单个字段进行过滤,例如通用名称、物种等。

我的

urls.py

urlpatterns = [
    path('project/family=<str:family>/', views.SpeciesDetail_family.as_view(), name='family'),
    path('project/species=<str:species>/', views.SpeciesDetail_species.as_view(), name='species')
]

还有

views.py

class SpeciesDetail_species(generics.ListAPIView):
    serializer_class = SpeciesSerializer

    def get_queryset(self):
        queryset = Species.objects.filter()
        species = self.kwargs['species']
        if species is not None:
            queryset = queryset.filter(species__iexact=species)
        return queryset

class SpeciesDetail_family(generics.ListAPIView):
    serializer_class = SpeciesSerializer

    def get_queryset(self):
        queryset = Species.objects.all()
        family = self.kwargs['family']
        if family is not None:
            queryset = queryset.filter(family__iexact=family)
        return queryset

如何为这两条路径创建单个视图?因此,我只需要从 URL 中参数化查找字段(可以是科、物种等),如

/project/species=PlantSpecies/
/project/family=PlantFamily/

如果我将 kwargs 添加到像

path('project/family=<str:family>/', views.SpeciesDetail_family.as_view(), {'lu_field':'family'}, name='family')
这样的路径,我如何在视图中访问
lu_field

python django django-views
1个回答
0
投票

看一下下面的代码,看看它是否按照您想要的方式工作:

from rest_framework import generics
from .models import Species
from .serializers import SpeciesSerializer

class SpeciesDetail(generics.ListAPIView):
    serializer_class = SpeciesSerializer

    def get_queryset(self):
        queryset = Species.objects.all()
        # Access dynamic lookup field and value from kwargs
        lu_field = self.kwargs.get('lu_field')
        lu_value = self.kwargs.get('lu_value')

        # Filter the queryset dynamically
        if lu_field and lu_value:
            filter_kwargs = {f"{lu_field}__iexact": lu_value}
            queryset = queryset.filter(**filter_kwargs)

        return queryset

这是

urls

from django.urls import path
from . import views

urlpatterns = [
    path('project/<str:lu_field>=<str:lu_value>/', views.SpeciesDetail.as_view(), name='species_detail'),
]

© www.soinside.com 2019 - 2024. All rights reserved.