RelatedField (and their subclasses) do not support traversing relationships that can be null · Issue #5848 · encode/django-rest-framework (original) (raw)

This was introduced by #5518, and while the solutions there work on normal fields, RelatedField behaves differently:

try:
return get_attribute(instance, self.source_attrs)
except (KeyError, AttributeError) as exc:

vs

return get_attribute(instance, self.source_attrs)

An example of the problem can be reproduced with https://gist.github.com/gcbirzan/a968facbaf0969f4a9616942de7022dc

A Model1 instance with None for model2 will produce an exception.

I believe that the correct behaviour is for RelatedField.get_attribute to call super.

As a side note, this is very hacky to work around, you'll need to copy paste the code from RelatedField.get_attribute in your class, then call the Field.get_attribute, since obviously super won't work.

If there's some agreement that this is the solution, I can fix it, but I'm not 100% sure (given the reaction on the original ticket) if this is considered a bug.