我有一个Instructor
模型,它有一个Client
模型的多对多字段。 (Instructor.clients
)
模特:
class InstructorProfile(models.Model):
'''Instructor specific profile attributes
'''
# Fields
office_number = models.CharField(max_length=30, blank=True, null=True)
location = models.CharField(max_length=30)
last_updated = models.DateTimeField(auto_now=True, editable=False)
# Relationship Fields
user = models.OneToOneField(settings.AUTH_USER_MODEL,
related_name="instructor_profile",
on_delete=models.CASCADE)
clients = models.ManyToManyField('ClientProfile', blank=True)
我的序列化程序目前是:
class InstructorProfileSerializer(serializers.ModelSerializer):
class Meta:
model = models.InstructorProfile
fields = '__all__'
and viewset:
class InstructorProfileViewSet(viewsets.ModelViewSet):
"""ViewSet for the InstructorProfile class"""
queryset = models.InstructorProfile.objects.all()
serializer_class = serializers.InstructorProfileSerializer
permission_classes = [permissions.IsAuthenticated]
除了clients
所属的用户(Instructor
模型字段中提供)之外,我想阻止所有人访问Instructor.user
字段。
我怎样才能做到这一点?
答案 0 :(得分:0)
将此添加到您的InstructorProfileViewSet
:
...
def get_queryset(self):
if hasattr(self.request.user, 'instructor_profile'):
return models.InstructorProfile.objects.filter(user=self.request.user)
else:
return models.InstructorProfile.objects.none()
...如果我正确猜到你的InstructorProfile模型。
答案 1 :(得分:0)
执行此操作的一种方法是更改列表方法以在需要的位置设置client=None
。这样您就可以保留响应结构。它会是这样的:
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
for i in serializer.data:
if i['user'] != request.user.pk:
i['client'] = None
return Response(serializer.data)