我正在尝试将我的django应用程序重新系列。这是我发现令人讨厌的重复代码:
class EducationInfoViewSet(viewsets.ModelViewSet):
queryset = pf.education_info.objects.all()
serializer_class = EducationInfoSerializer
permission_classes = (VisionUserPermissions, )
def get_queryset(self):
model = pf.education_info
identity = self.request.query_params.get('username',None)
queryset = model.objects.all()
user = User.objects.none()
if identity is not None:
user = User.objects.get(username=identity)
student = get_object_or_404(dbd.user_type, username=user)
queryset = model.objects.filter(username=student)
if not permission_check(self.request,user):
return User.objects.none()
return queryset
class FamilyInfoViewSet(viewsets.ModelViewSet):
queryset = pf.family_info.objects.all()
serializer_class = FamilyInfoSerializer
permission_classes = (VisionUserPermissions, )
def get_queryset(self):
model = pf.family_info
identity = self.request.query_params.get('username',None)
queryset = model.objects.all()
user = User.objects.none()
if identity is not None:
user = User.objects.get(username=identity)
student = get_object_or_404(dbd.user_type, username=user)
queryset = model.objects.filter(username=student)
if not permission_check(self.request,user):
return User.objects.none()
return queryset
所以我的" get_queryset"函数除了一个变量以外的其他相同,而且我有多个类似的类。我应该如何在不重复自己的情况下实施此操作?
预先感谢!
创建一个混合类
class QuerysetMixin(viewsets.ModelViewSet):
def get_queryset(self):
model = getattr(pf, self.field_name)
identity = self.request.query_params.get('username',None)
queryset = model.objects.all()
user = User.objects.none()
if identity is not None:
user = User.objects.get(username=identity)
student = get_object_or_404(dbd.user_type, username=user)
queryset = model.objects.filter(username=student)
if not permission_check(self.request,user):
return User.objects.none()
return queryset
并继承
class FamilyInfoViewSet(viewsets.ModelViewSet, QuerysetMixin):
queryset = pf.family_info.objects.all()
serializer_class = FamilyInfoSerializer
permission_classes = (VisionUserPermissions, )
field_name = 'family_info'