Django RF ModelSerializer获取当前用户的userid

ruarlubt  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(158)

我想把我所有的创建、更新方法从我的视图移到serializer.py,我读到了保持你的视图瘦,而序列化器胖。

class APIClerkView(generics.ListCreateAPIView):
permission_classes = [IsAuthenticated]
serializer_class = ClearanceItemSerialize

  def perform_create(self, serializer):
     serializer.save(recorded_by=self.request.user.userid)

这里我有一个简单的create,它将当前用户userid保存到recorded_by,我如何在我的ModelSerializer中实现这一点
编辑:对于我的更新方法,我使用了instance.resolve等...如果有两个返回***instance***和***super().create(validated_data)***,我如何才能使其正常工作

def update(self, instance, validated_data):
    instance.resolve = 'True'
    instance.resolve_date = timezone.now()
    validated_data.resolve_by = self.context["request"].user.userid 
    

    TransactionLog.objects.create(cl_itemid=ClearanceItem.objects.get(cl_itemid=instance.cl_itemid),
      trans_desc="Resolve Clearance Item",
      trans_recorded=timezone.now())
    return instance
    return super().create(validated_data)

编辑2:

def update(self, instance, validated_data):
    instance.resolve = 'True'
    instance.resolve_date = timezone.now()
    instance.resolve_by = validated_data.get(self.context["request"].user.userid, instance.resolve_by)
    instance.save()
    return instance

编辑:我用这个来让它工作

def update(self, instance, validated_data):
    instance.resolve = 'True'
    instance.resolve_date = timezone.now()
    instance.resolve_by = self.context["request"].user.userid

    TransactionLog.objects.create(cl_itemid=ClearanceItem.objects.get(cl_itemid=instance.cl_itemid),
      trans_desc="Resolve Clearance Item",
      trans_recorded=timezone.now())
    instance.save()
    return instance
mkshixfv

mkshixfv1#

只要覆写序列化程式的**create(...)**方法

class ClearanceItemSerialize(serializers.ModelSerializer):
    # other fields and meta
    def create(self, validated_data):
        # attach the user to the validated data
        validated_data["recorded_by"] = self.context["request"].user
        return super().create(validated_data)

相关问题