How do you override get_queryset ModelViewSet in Django Rest Framework 3?

I used this template in the Django Rest Framework (DRF) 2:

class Foo(models.Model): user = models.ForeignKey(User) class FooSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Foo fields = ('url') class FooViewset(viewsets.ModelViewSet): def get_queryset(self): return Foo.objects.filter(user=self.request.user) serializer = FooSerializer model = Foo # <-- the way a ModelViewSet is told what the object is in DRF 2 [ in urls.py] from rest_framework import routers router = routers.DefaultRouter() router.register('Foo', views.FooViewSet) 

In DRF 3, I now get:

 AssertionError at / `base_name` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute. 

How is get_queryset overridden for an instance of rest_framework.viewsets.ModelViewSet ?

+8
django-rest-framework
source share
2 answers

Figured it out. The model rest_framework.viewsets.ModelViewSet looks like AWOL in DRF3. Now, if you override get_queryset , you need to specify the third parameter routers.DefaultRouter().register , which is the basename parameter. Then the function will not disappear and will try to find it in the nonexistent field of queryset ModelViewSet .

+8
source share

To override the default query in DRF 3, simply define the queryset attribute in your FooViewSet class.

 class FooViewset(viewsets.ModelViewSet): queryset = Foo.objects.all() 
0
source share

All Articles