Django REST框架 - 过滤URL

时间:2017-12-18 17:41:34

标签: python django django-rest-framework

我正在使用带有Django 1.11的Django REST框架工具包,我正在尝试根据网址过滤结果。这是我的设置:

models.py

from django.db import models

class Package(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
    return self.name

serializers.py

from rest_framework import serializers
from .models import Package

class PackageSerializer(serializers.ModelSerializer):
      class Meta:
            model = Package
            fields = ('name',)

views.py

from rest_framework import viewsets
from .models import Package
from .serializers import PackageSerializer

class PackageViewSet(viewsets.ReadOnlyModelViewSet):
     serializer_class = PackageSerializer
     queryset = Package.objects.all()

urls.py

from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'package', views.PackageViewSet)

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/v1/', include(router.urls)),
]

目前,当我使用它时,我可以通过id字段过滤结果:

http://127.0.0.1:8000/api/v1/package/1/

我希望通过我的包模型的名称字段来过滤结果,而不是使用它:

http://127.0.0.1:8000/api/v1/package/basic/

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

在视图集中设置lookup_field属性,请参阅the documentation

class PackageViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = PackageSerializer
    queryset = Package.objects.all()
    lookup_field = 'name'

答案 1 :(得分:0)

在视图中使用filter_fields。

return new StringParameterValue(
  getName(), 
  defaultValue == null ? choices.get(0) : defaultValue, getDescription()
);

查找字段用于默认设置查找,它将是模型 filter_fields = ('name',)

如果您想创建您的网址,

pk

设置my_url/filter_field/

如果您想从URL中搜索,

lookup_field = "name"

您需要在视图中设置my_url/?name=something