Nested Serializer Scenario: What is the best? #4
giuseppenovielli
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello everyone,
in a complex scenario, we need to save or update nested objects.
Please consider the following two models.
How you can read into the model: CarUser there are some custom business logic into clean() method.
The method
def _car_user_validator(self)
requiredCar
instance to continue the validation.Now, when i want to save 'nested serializers', considering call POST rest api, this mean that i save a new object
Car
and this Car instance must be associate toCarUser
at field car.The following json is more clear what i mean:
s = CarFullCleanSerializer(data=request.POST)
s.is_valid(raise_exception=True)
s.save()
This code got an Exception
Exception: Nested serializers are not supported.
FAIL
This code got an Exception
CarUser.car.RelatedObjectDoesNotExist: CarUser has no car.
CarUser
model, intodef _car_user_validator(self)
method need to have aCar
instance, if you don't provide it, theCarUser
instance can't be saved into db, because we don't know if the data trust own business logic!FAIL
is_valid(extra_include=None)
parameter:YES now CarUser is validated our data before save, but if
CarUser clean()
fail orModelSerializer.validate()
method fail?A
Car
instance is already save!! But our endpoint get 400 Bad Request!FAIL
is_valid(extra_include=None)
parameter using partial instance:Ok, now we don't save
Car
, if all our instance are validated!Warning!
If use this hack you must design
CarUser.clean()
method for example, without perform filter, becauseCar
instance isn't saved into db.This is not the solution, but is a good hack to prevent the bad save, as described above at point 3.
Still investigating when there are
Unique constraint
.What do you think?
I need your opinion.
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions