使用 Django Rest Framework 实现视图或方法的简洁方法

Clean way to implement views or methods with Django Rest Framework

我正在尝试为我的 ViewSet 实现一些特定的视图,但要保持简洁优雅的代码。我有一些服务器和一些数据中心;

models.py

class Datacenter(models.Model):

    name = models.CharField(max_length=50)
    status = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

class Server(models.Model):

    datacenter = models.ForeignKey(Datacenter,related_name="servers")
    hostname = models.CharField(max_length=50)

    def __unicode__(self):
        return self.hostname

serializers.py

class ServerSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Server

class DatacenterSerializer(serializers.ModelSerializer):
    Servers = ServerSerializer(many=True)
    class Meta:
        model = Datacenter
        fields = ('id', 'name','status','Servers')

views.py

class DatacenterViewSet(viewsets.ModelViewSet):

    queryset = Datacenter.objects.all()
    serializer_class = DatacenterSerializer

class ServerViewSet(viewsets.ModelViewSet):

    queryset = Server.objects.all()
    serializer_class = ServerSerializer

urls.py

router = routers.DefaultRouter()
router.register(r'Enviroment', views.EnviromentViewSet)
router.register(r'Server', views.ServerViewSet)

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

所以我想要实现的一个清晰示例是一个数据中心中所有服务器的视图,例如;

/datacenter/{id}/servers

我检查了其他类似的问题,例如this one and this one but I'm not sure those are actually the best ways, also I was unable to make it work as described in the answer given by mariodev

我试图避免使用 url 模式来解决这个问题,例如 Tom Dickin suggested

据我所知,这可以使用 viewsets, routers or generic-views

来解决

最简单的解决方案是什么?有人能给我指出正确的方向吗?

您可以使用临时方法

serializers.py

class ServerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Server

class DatacenterSerializer(serializers.ModelSerializer):
    servers = ServerSerializer(many=True)
    class Meta:
        model = Datacenter
        fields = ('id', 'name','status','servers')

views.py

class DatacenterViewSet(viewsets.ModelViewSet):

    queryset = Datacenter.objects.all()
    serializer_class = DatacenterSerializer

    @detail_route(methods=['get'], permission_classes=[permissions.IsAdminUser])
    def servers(self, request, pk=None):
        servers = Server.objects.filter(datacenter__id=pk)
        serializer = ServerSerializer(servers, many=True, context={'request': request})
        return Response(serializer.data)

urls.py

router = routers.DefaultRouter()
router.register(r'Enviroment', views.EnviromentViewSet)
router.register(r'server', views.ServerViewSet)
router.register(r'datacenter', views.DatacenterViewSet)

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