使用SimpleRouter在ViewSet中出现Django错误

时间:2016-08-28 02:05:28

标签: python django-rest-framework

views.py

from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import generics
from ticker.serializers import PriceSerializer
from ticker.models import Price
import datetime
from nexchange.settings import DEFAULT_HOUR_RANGE


class LastPricesViewSet(viewsets.ViewSet):
    def list(self, request):
        queryset = Price.objects.filter().order_by('-id')[:2]
        serializer = PriceSerializer(queryset, many=True)
        return Response(serializer.data)


class PriceHistoryViewSet(generics.ListAPIView):
    serializer_class = PriceSerializer

    def get_queryset(self, request):
        hours = self.request.query_params.get('hours', DEFAULT_HOUR_RANGE)
        relevant = datetime.datetime.now() - datetime.timedelta(seconds=hours * 3600)
        queryset = Price.objects.filter(created_on__gte=relevant).order_by('id')
        return queryset

urls.py:

from rest_framework.routers import SimpleRouter
from ticker.views import LastPricesViewSet, PriceHistoryViewSet

router = SimpleRouter()
router.register(r'price/latest', LastPricesViewSet, base_name='latest')
router.register(r'price/history', PriceHistoryViewSet, base_name='history')
api_patterns = router.urls

runserver期间出现以下错误(没有basename kwarg): AssertionError: {BASE_NAME {1}}。{查询集{1}}

但是,当我添加希望的argument not specified, and could not automatically determine the name from the viewset, as it does not have a时,错误会更改为: attribute.

我怀疑它可能与在一个路由器中组合ViewSet和ListAPIView有关。

1 个答案:

答案 0 :(得分:3)

解决方案: 您必须从viewsets.ViewSetMixin继承以实现ViewSetClass向DRF路由器注册所需的方法,否则可以使用简单的Django urlconf表示法。

views.py:

class PriceHistoryViewSet(viewsets.ViewSetMixin, generics.ListAPIView):
    serializer_class = PriceSerializer

    def get_queryset(self, *args, **kwargs):
        hours = self.request.query_params.get('hours', DEFAULT_HOUR_RANGE)
        relevant = datetime.datetime.now() - datetime.timedelta(seconds=hours * 3600)
        queryset = Price.objects.filter(created_on__gte=relevant).order_by('id')
        return queryset

urls.py:

from rest_framework.routers import SimpleRouter
from ticker.views import LastPricesViewSet, PriceHistoryViewSet

router = SimpleRouter()
router.register(r'price/latest', LastPricesViewSet, base_name='latest')
router.register(r'price/history', PriceHistoryViewSet, base_name='history')
api_patterns = router.urls