1. View 中使用 多个路径参数

http://www.django-rest-framework.org/api-guide/generic-views/#creating-custom-mixins

1
2
3
4
5
6
7
8
9
10
11
12
13
class MultipleFieldLookupMixin(object):
"""
Apply this mixin to any view or viewset to get multiple field filtering
based on a `lookup_fields` attribute, instead of the default single field filtering.
"""
def get_object(self):
queryset = self.get_queryset() # Get the base queryset
queryset = self.filter_queryset(queryset) # Apply any filter backends
filter = {}
for field in self.lookup_fields:
if self.kwargs[field]: # Ignore empty fields.
filter[field] = self.kwargs[field]
return get_object_or_404(queryset, **filter) # Lookup the object

创建视图的时候使用这个混合类,创建的url包含account,username路径参数/(?P<account>.+)/(?P<username>.+)

1
2
3
4
class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_fields = ('account', 'username')

覆盖授权

1
2
3
class UploadView(APIView):
authentication_classes = (BasicAuthentication,) # 用其他认证类取消jwt的授权
permission_classes = (AllowAny,)

显示复数

使用中文翻译的时候需要要指定复数命名,否则会自动在app label后面添加s

1
2
class Meta:
verbose_name_plural = verbose_name