Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework custom validation function on ForeignKey field is not called

I have a ModelSerializer that has a ForeignKey field. This is the code for the model:

class Attendance(models.Model):
    employee = models.ForeignKey(Employee, related_name='attendance_times')
    datetime = models.DateTimeField()

and this is the serializer:

class AttendanceSerializer(serializers.ModelSerializer):

    def validate_employee(self, value):
        try:
            Employee.objects.get(pk=value)
        except Employee.DoesNotExist:
            Employee.objects.create(pk=value)
        return value

    class Meta:
        model = Attendance
        fields = ('employee', 'datetime')

the problem is when I send a post request to create a new object, the function validate_employee is not called and the serializer returns a validation error saying:

Invalid pk "1321" - object does not exist.

Why is this happening? Am I doing something wrong? Is there another validator that is being called before my validator?

like image 498
Navid777 Avatar asked Apr 05 '26 19:04

Navid777


2 Answers

There are a couple of things that happen before you the validate_<field> is called.

In particular, the field itself will perform an initial validation check and cast the incoming data into Python object. With PrimaryKeyRelatedField it'll check the associated model and return the instance.

like image 100
Linovia Avatar answered Apr 08 '26 07:04

Linovia


I think you need to call save() function after creating the instance.

    except Employee.DoesNotExist:
        employee = Employee.objects.create(pk=value)
        employee.save()
    return value
like image 35
abyanburhanuddin Avatar answered Apr 08 '26 09:04

abyanburhanuddin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!