Home > Mobile >  Django,update the same row field in model getting data from serializer
Django,update the same row field in model getting data from serializer

Time:09-12

I have this model:

class AgentDetail(MethodID):

    first_name = models.CharField(max_length=50, blank=True, null=True, unique=True)
    last_name = models.CharField(max_length=50, unique=True, null=True)
    email = models.EmailField(null=False)
    authen_method = models.ForeignKey(AuthMethodID, on_delete=models.CASCADE)
    country_code = models.BigIntegerField(default=1)
    mobile_number = models.BigIntegerField(null=False)
    sms_provider = models.CharField(max_length=50, null=True)
    active_status = models.BooleanField(default=True)
    created_time = models.DateTimeField(default=now, editable=False)
    created_by = models.CharField(max_length=50)
    updated_time = models.DateTimeField(auto_now=True)
    updated_by = models.CharField(max_length=50)

and this serializer:

class AgentSerializer(serializers.ModelSerializer):
    class Meta:
        model = AgentDetail
        fields = [
            "first_name",
            "last_name",
            "email",
            "authen_method",
            "mobile_number",
            "sms_provider",
        ]

and this views.py:

@api_view(["POST"])
def create_agent(request):
    if request.method == "POST":
        serializer = AgentSerializer(data=request.data, many=False)
        if serializer.is_valid():
            serializer.save()
            request_data = serializer.data
            # AgentDetail.objects.update_or_create(
            #     created_by=request_data["first_name"]   request_data["last_name"],
            #     updated_by=request_data["first_name"]   request_data["last_name"],
            # )
            return Response(status=status.HTTP_200_OK)
        error = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        return error

As in serializer I'm not passing created_by field and I need that field gets value of first_name last_name which are coming from serializer data.I'm new to DRF.

CodePudding user response:

you can access the validated_data in create method, and add any extra data you want.

serializer.py

class AgentSerializer(serializers.ModelSerializer):
    ...

    def create(self, validated_data):
        first_name = validated_data.get('first_name', '')
        last_name = validated_data.get('last_name', '')
        validated_data.update(dict(
            created_by=first_name last_name,
            updated_by=first_name last_name
        ))
        return super().create(validated_data)

CodePudding user response:

as said in docs you can pass additional attributes to save method.

views.py

@api_view(["POST"])
def create_agent(request):
    if request.method == "POST":
        serializer = AgentSerializer(data=request.data, many=False)
        if serializer.is_valid():
            request_data = serializer.data
            serializer.save(
                created_by=request_data["first_name"]   request_data["last_name"],
                updated_by=request_data["first_name"]   request_data["last_name"],
            )
            return Response(status=status.HTTP_200_OK)
        error = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        return error
  • Related