有一个Plan具有用户字段的模型,我想用用户的令牌填充用户字段,以便用户无法发送用户id为另一个用户创建模型,而只是为自己发送发布请求,这是我的模型:class Plan(models.Model):"""Plan object"""user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE)我的观点是:class PlanViewSets(viewsets.ModelViewSet):"""A viewset for non-admin user see list and admin can curd plan model"""model = Planqueryset = Plan.objects.all().order_by('-id')serializer_class = serializers.PlanSerializerpermission_classes = (IsAuthenticated,)authentication_classes = (TokenAuthentication,)def get_queryset(self): """retrieve plan just for its own user who is authenticated already""" return self.queryset.filter(user=self.request.user)如何Plan只为用户创建而不user通过请求正文获取字段?
1 回答
素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
你想要的是perform_create方法:
class PlanViewSets(viewsets.ModelViewSet):
"""A viewset for non-admin user see list and admin can curd plan model"""
model = Plan
queryset = Plan.objects.all().order_by('-id')
serializer_class = serializers.PlanSerializer
permission_classes = (IsAuthenticated,)
authentication_classes = (TokenAuthentication,)
def get_queryset(self):
"""retrieve plan just for its own user who is authenticated already"""
return self.queryset.filter(user=self.request.user)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
添加回答
举报
0/150
提交
取消