我试图重新考虑我的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"除了一个变量之外,函数是相同的,我有多个这样的类。我应该如何实现这一点而不重复自己?
提前致谢!
答案 0 :(得分:0)
创建一个混音类
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'