Setting the 'instance' attribute for nested model serializers

41 views
Skip to first unread message

Petros Moisiadis

unread,
Jun 14, 2016, 9:45:01 AM6/14/16
to Django REST framework
Hello,

I am trying to implement some writable nested model serializers. I am talking about a scenario in which a parent model serializer includes nested model serializers for some related fields in the parent serializer's model. The nested model serializers may in turn be the parent for other nested model serializers for related fields one level down, and so on.

I have already implemented the logic for creation and update as I need it. The problem comes when I need to do some validations on my nested model serializers, e.g. to check for uniqueness on some field combination. To do that I need to access the nested model serializer's instance (e.g. to check that the 'incoming' primary key field matches the saved object's primary key). However, the 'instance' attribute is only set for the parent serializer that is at the top of the hierarchy (the one that is bound to generic views). All nested model serializers that are nested into the parent serializer have their 'instance' attribute not set (it is always None), although their fields are correctly populated with corresponding data from the saved object.

I think that when initializing model serializers based on a model instance, there should be logic to recursively set the 'instance' attribute for any nested model serializer that maps to a related field of its parent. I believe this would be very useful for people implementing writable nested model serializers. So, is this a feature that has not yet been implemented in the framework (or could it be that I am doing something wrong)? Are other people insterested in this? Has anybody tackled with it before?

Tom Christie

unread,
Jun 14, 2016, 10:54:37 AM6/14/16
to Django REST framework
I've just recently added some documentation related to that, in this pull request...


See the 'Limitations of validators ... Updating nested serializers' section.

Right now the answer is just "you need to deal with this validation explicitly".
It's possible that we *could* try to do a better job of dealing with this automagically. I'm a little wary of doing so, as I wouldn't be surprised if we ended up bumping into unexpected edge-cases if we did, but I'd be open to exploratory pull requests. (Or it may simply be worth putting onto the backlog in any case)

Cheers,

  Tom

Reply all
Reply to author
Forward
0 new messages