Search code examples
pythondjangodjango-rest-framework

Django serializer is not validating or saving data


I am trying to save data in the database, it works for most of my models but for few models I am not sure why but django is not serializing data. I hope someone can point out where I might be doing wrong. Here is my code

Django Models

class UserModel(AbstractUser):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False)

class UserWorkPresenceModel(models.Model):
    user = models.ForeignKey("UserModel", on_delete=models.CASCADE, related_name="workpresence")
    is_active = models.BooleanField(default=False)
    check_in = models.DateTimeField(blank=False)
    check_out = models.DateTimeField(blank=True, null=True)
    work_break = []

class UserWorkBreakModel(models.Model):
    work_presence = models.ForeignKey("UserWorkPresenceModel", on_delete=models.CASCADE, related_name="work_break")
    start_break = models.DateTimeField(blank=True)
    end_break = models.DateTimeField(blank=True, null=True)
    is_current_break = models.BooleanField(default=False)

Serializer:

class UserTakeBreakSerializer(serializers.Serializer):
    class Meta:
        model = UserWorkBreakModel
        # fields = ("start_break", "end_break")
        fields = '__all__'

API View

class UserStartWorkBreakView(APIView):
    def post(self, request, id):
        try:
            user = UserModel.objects.get(uuid=id)
        except:
            return Response({'message': 'User not found'}, status=HTTP_400_BAD_REQUEST)
        try:
            work_presence = UserWorkPresenceModel.objects.get(user=user, is_active=True)
        except UserWorkPresenceModel.DoesNotExist:
            return Response({'message': 'User work presence not found'}, status=HTTP_400_BAD_REQUEST)
        currently_onbreak = UserWorkBreakModel.objects.filter(work_presence=work_presence, is_current_break=True)
        if currently_onbreak.exists():
            return Response({'message': 'User already working'}, status=HTTP_400_BAD_REQUEST)
        serializer = UserTakeBreakSerializer(data=request.data)
        print(serializer)
        if serializer.is_valid():
            print(f'validated_data: {serializer.validated_data}')
            user.workpresence_status = UserWorkPresenceStatus.ON_BREAK
            serializer.validated_data['is_current_break'] = True
            serializer.save(work_presence=work_presence)
            user.save()
            print(f'serializer.data: {serializer.data}')
            return Response(serializer.data, status=HTTP_201_CREATED)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

I'm not getting any error just empty dictionary, here is result of my print commands:

UserTakeBreakSerializer(data={'start_break': '2024-05-10 15:05:52.829867'}):
validated_data: {}
serializer.data: {}

You might find it funny but I have implemented same logic for UserWorkPresenceModel and it is working fine, I'm able to do both create and update for UserWorkPresenceModel. And it is not just this, I'm having same trouble with another model, one is working while the same logic is not working in other model which quite similar.

Thank you for you help


Solution

  • Use a ModelSerializer [drf-doc]. For a simple serializer, you will have to write the boilerplate code yourself:

    class UserTakeBreakSerializer(serializers.ModelSerializer):
        class Meta:
            model = UserWorkBreakModel
            fields = '__all__'

    essentially what happened was that you defined an empty serializer: a serializer with no fields, and no save logic. A ModelSerializer on the other hand looks at the Meta and then builds the fields and the corresponding logic for that model.