使用Django 1.11& djangorestframework == 3.7.7,我想在GET调用中返回is_thumbnail = True的视频。但是,我使用过滤器进行的所有测试都返回了所有视频对象。
型号:
class Videos(models.Model):
"""This class represents the Videos model."""
uid = models.UUIDField(
primary_key=True, default=uuid.uuid4, editable=False)
is_thumbnail = models.BooleanField(default=False)
file_name = models.CharField(unique=True, max_length=64)
file_path = models.CharField(unique=True, max_length=256)
file_created_time = models.DateTimeField()
owner = models.ForeignKey('auth.User',
related_name='videos',
on_delete=models.CASCADE)
created_time = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""Return a human readable representation of the model instance."""
return "{}".format(self.file_name)
视图:
class DetailsView(generics.RetrieveUpdateDestroyAPIView):
"""This class handles the http GET, PUT and DELETE requests."""
serializer_class = VideosSerializer
permission_classes = (permissions.IsAuthenticated, IsOwner)
lookup_field = 'uid'
def get_queryset(self):
return Videos.objects.filter(is_thumbnail=True)
如果我在get_queryset函数中放置一个print语句,我在日志中看不到该语句。所以看起来这个函数没有被调用。
API / urls.py
urlpatterns = {
url(r'^auth/', include('rest_framework.urls',
namespace='rest_framework')),
url(r'^api/videos/$', CreateView.as_view(), name="create"),
url(r'^api/videos/(?P<uid>[0-9a-f-]+)/$',
DetailsView.as_view(), name="details"),
url(r'^get-token/', obtain_auth_token),
}
securedash_project / urls.py
urlpatterns = format_suffix_patterns(urlpatterns)
urlpatterns = [
url(r'', include('secureDash.dash.urls')),
url(r'^dash/', include('secureDash.dash.urls')),
url(r'^admin/', admin.site.urls),
url(r'^', include('secureDash.api.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
答案 0 :(得分:0)
好的,你想要替换&#34; get_queryset&#34;的值。通用视图&#34; generics.RetrieveUpdateDestroyAPIView&#34;的方法,它使用&#34; uid&#34;来访问对象。像lookup_field这样的字段设置稍后进行修改,所以我建议当你覆盖它时,&#34; get_queryset&#34;方法用以下内容替换它们:
def get_queryset(self):
return self.get_queryset().filter(is_thumbnail=True)
答案 1 :(得分:0)
我遇到的问题是我有一个实现generics.ListCreateAPIView的CreateView类。这个视图有r / w端点,所以我的GET调用永远不会到达我的DetailsView。我需要调整我的观点,但现在这只能显示is_thumbnail =真实视频。
class CreateView(generics.ListCreateAPIView):
"""This class defines the (GET & POST) behavior of the rest api."""
serializer_class = VideosSerializer
permission_classes = (permissions.IsAuthenticated, )
def perform_create(self, serializer):
"""Save the post data when creating a new Videos object."""
serializer.save(owner=self.request.user)
def get_queryset(self):
queryset = Videos.objects.all()
return queryset.filter(is_thumbnail=True)
class DetailsView(generics.RetrieveUpdateDestroyAPIView):
"""This class handles the http GET, PUT and DELETE requests."""
queryset = Videos.objects.all()
serializer_class = VideosSerializer
permission_classes = (permissions.IsAuthenticated, IsOwner)
lookup_field = 'uid'