Validation of child runs twice. Is this deliberate as it seems a bit inefficient to run the same code twice.
Firstly, huge thanks for the code.
I have a small question. Given two serializers: a parent and a child, inserting a validate method in the child serializer and printing something from there reveals that the function is called twice. Is this deliberate as it seems a bit inefficient to run the same code twice.
Something else that I am observing is that, when performing update operations, the first run of validate on a child does not have self.instance set but the second run does. I am checking self.instance. I check the value of self.instance to determine some conditional validation behavior during updates with the assumption that an object being updated will have self.instance set.
Something else that I am observing is that, when performing update operations, the first run of
validateon a child does not haveself.instanceset but the second run does. I am checkingself.instance. I check the value ofself.instanceto determine some conditional validation behavior during updates with the assumption that an object being updated will haveself.instanceset.
Oh yeah. I was also actually trying to use self.instance when I realised that it runs twice. I'm, for now, ignoring the validation when there is no self.instance; I don't know what the consequences of that are going to be.
I have conditional validation that changes depending upon whether the child was being updated or created and I am reliant on self.instance to know what validation to perform. Having the duplicate validation runs occur but with inconsistent value for self.instance was causing me a headache. My quick and dirty resolution is to eagerly check for the object's existence if self.instance is not defined. This isn't ideal since it will lead to unnecessary queries being run but it gets the job done.
Example:
def validate(self, data):
pk = data.get('id') or data.get('pk')
self_exists = bool(self.instance) or self.Meta.model.objects.filter(pk=pk).exists()
The only alternative that I can see is what you're doing @tomgwasira: ignore/skip validation if pk or id has a value but self.instance is not set yet.
The same situation applies when I try to use self.parent or self.root in child's validation. The first validation (seems to be run by DRF) is correct, while in the second validation (seems to be run by drf-writable-nested) does not have neither self.parent nor self.root.
It could be very useful if you split code in update_or_create_reverse_relations of BaseNestedModelSerializer into several function calls so that users are able to override only needed methods instead of copypasting whole 66-line long method to change only a few lines.
Would love to see a fix for this. I see a PR exists to address it currently https://github.com/beda-software/drf-writable-nested/pull/174 but not sure if it is the ideal solution.