很多时候业务需求并不是几个简单的mixin就可以满足,需要我们自定义mixin
# get_object源码中字段查询源代码
filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
obj = get_object_or_404(queryset, **filter_kwargs)
# 自定义多字段查询mixin
class MultipleFieldLookupMixin(object):
# 重写GenericAPIView里面的 get_object
def get_object(self):
queryset = self.get_queryset()
queryset = self.filter_queryset(queryset)
filter = {} # 重新字段部分代码,原来是只有一个字段,使用循环处理返回多个字段
for field in self.lookup_fields:
if self.kwargs[field]:
filter[field] = self.kwargs[field]
obj = get_object_or_404(queryset, **filter)
self.check_object_permissions(self.request, obj)
return obj
# 继承自定义多字段查询mixin class RetrievePostView(MultipleFieldLookupMixin,generics.RetrieveAPIView): queryset = Post.objects.all() serizlizer_calss = PostSerializer lookup_fields = ('pk','title') # 多字段
# 继承自定义多字段查询mixin
class RetrievePostView(MultipleFieldLookupMixin,generics.RetrieveAPIView):
queryset = Post.objects.all()
serizlizer_calss = PostSerializer
lookup_fields = ('pk','title') # 多字段
#url视图匹配多个字段
path('posts/<int:pk>/<str:title>', RetrievePostView.as_view()),