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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With