django-rest-framework自定义视图集与多个查找参数检索

时间:2018-07-04 13:46:49

标签: django django-rest-framework django-rest-viewsets

我有两个模型,分别是A和B。

模型外观

<MouseBinding Command="{Binding DataContext.EngineerCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}" ... />

序列化器

class A(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=1000)
    slug = models.CharField(max_length=100)

class B(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=1000)
    slug = models.CharField(max_length=100)
    A = models.foreignkey(A, models.SET_NULL, blank=true)

模型视图集

Class ASerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
         model = A
         fields = '__all__'
         lookup_field = 'slug'
         extra_kwargs = {'url': {'lookup_field': 'slug'}}


Class BSerializer(serializers.ModelSerializer):
    class Meta:
         model = B
         fields = '__all__'

我想访问

之类的网址

from rest_framework import viewsets, permissions from rest_framework.response import Response from rest_framework.decorators import action from .models import (A, B) from .serializers import (ASerializer, BSerializer) Class AViewSet(viewsets.ModelViewSet): queryset = A.objects.all() serializer_class = ASerializer permission_classes = (permissions.DjangoModelPermissionsOrAnonReadOnly, ) lookup_field = 'slug' def retrieve(self, request, *args, **kwargs): instance = self.get_object() bs = B.objects.filter(A=instance.id) serializer = BSerializer(bs, many=True) return Response(serializer.data)

我浏览了Django Restframework文档,发现我们可以添加自定义url,例如{drf-custom-rounting。我上面没有获得如何制作访问url模式的方法。

如何自定义?

编辑: 我已经解决了我的问题。我找到了类似类型的问题解决方案here。感谢您的答复。

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找一种制作嵌套网址的方法。

DRF文档建议的方式是使用此软件包:https://github.com/alanjds/drf-nested-routers

用法示例:

首先,您创建视图集:

Class BViewSet(viewsets.ModelViewSet):
     queryset = B.objects.all()
     serializer_class = BSerializer
     lookup_field = 'slug'

     def retrieve(self, request, a_slug=None, b_slug=None):
          a = self.get_object()
          # Now you retrieve all B related to A
          bs = B.objects.filter(A=a)
          serializer = BSerializer(bs, many=True)
          return Response(serializer.data)

然后您使用drf-nested-routers注册视图集:

from rest_framework_nested import routers

from .viewsets import AViewSet, BViewSet

a_router = routers.SimpleRouter()
a_router.register(r'A', AViewSet)

b_router = routers.NestedSimpleRouter(a_router, r'B')
b_router.register(r'B', BViewSet)

urlpatterns = patterns('',
    url(r'^', include(a_router.urls)),
    url(r'^', include(b_router.urls)),
)

答案 1 :(得分:0)

在您的urls.py

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

router = routers.DefaultRouter()
router.register(r'yourregex', views.AViewSet)

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