Home > Software design >  Django RF ModelSerializer get current user's userid
Django RF ModelSerializer get current user's userid

Time:11-15

I want to move all my create,update method from my views to serializer.py, I read keep your views thin while serializer fat.

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

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

here I have simple create that save the current user userid to recorded_by, How can I do that in my ModelSerializer

Edit: For my update method I was using instance.resolve etc... how can I make this work if there's two return both instance and 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)

Edit2:

    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

Edit: I got it working by using this

    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

CodePudding user response:

Simply override the create(...) method of the serializer

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)
  • Related