Referencing relation's relations in Django Serializer
<p>Let's say I have some models:</p>

<pre><code>class A(models.Model):
    ...

class B(models.Model):
    my_reference_to_a = models.ForeignKey(A)
    b_field_1 = ...
    b_field_2 = ...

class C(models.Model):
    my_reference_to_b = models.ForeignKey(B)
    c_field_1 = ...
    ...
</code></pre>

<p>In my serializer for <code>C</code>, I want to include all of the fields in <code>C</code>, all the fields in <code>B</code>, as well as the reference to <code>A</code> in <code>B</code> (but not the reference to <code>B</code> in <code>C</code>), so the JSON API output would be something like this:</p>

<pre><code>{
    "data": [{
        "type": "C",
        "id": "1",
        "attributes": {
            "b_field_1": "...",
            "b_field_2": "...",
            "c_field_1": "..."
        },
        "relationships": {
            "a": {
                "data": {
                    "type": "A",
                    "id": "1"
                }
            }
        }
    }],
    ...
}
</code></pre>

<p>How would I go about this? I've already tried doing something like this inside my serializer for <code>C</code>:</p>

<pre><code>A = ASerializer(source='my_reference_to_b.my_reference_to_a')
</code></pre>

<p>But that doesn't work, as DRF doesn't seem to support dotted paths for sources. I've also tried supplying a method that returns the proper model (the model is valid inside the method) as the source, but that outputs the reference in the JSON as:</p>

<pre><code>"a": {
    "data": null
}
</code></pre>

<p>On my <code>A</code> model, I also have a reference to another model, <code>D</code>, that is not explicitly stated in <code>A</code>, but is instead defined in <code>D</code> as a OneToMany relationship (Many <code>D</code> models to one <code>A</code> model) with a resource_name on the ForeignKey declared in <code>D</code>, and trying to reference this in <code>C</code> to include that relationship in the JSON doesn't work, either. I get this error (trying to reference it by doing <code>D = DSerializer(source='B.D')</code>):</p>

<pre><code>'RelatedManager' object has no attribute 'B'
</code></pre>

<p>Any help would be greatly appreciated.</p>

<p>I figured it out. Just answering my own question in case anyone lands on this page and they need help.</p>

<p>You need to use the SerializerMethodResourceRelatedField from the Django Rest Framework JSON API. I had tried the regular ResourceRelatedField without it working, looking through the source code showed me that ResourceRelatedField doesn't support dotted paths. Instead, use SerializerMethodResourceRelatedField with a source pointing to a method that returns the desired relation.</p>

python django ember.js django-rest-framework json-api