Let's say I have some models:
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 = ...
...
In my serializer for C
, I want to include all of the fields in C
, all the fields in B
, as well as the reference to A
in B
(but not the reference to B
in C
), so the JSON API output would be something like this:
{
"data": [{
"type": "C",
"id": "1",
"attributes": {
"b_field_1": "...",
"b_field_2": "...",
"c_field_1": "..."
},
"relationships": {
"a": {
"data": {
"type": "A",
"id": "1"
}
}
}
}],
...
}
How would I go about this? I've already tried doing something like this inside my serializer for C
:
A = ASerializer(source='my_reference_to_b.my_reference_to_a')
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:
"a": {
"data": null
}
On my A
model, I also have a reference to another model, D
, that is not explicitly stated in A
, but is instead defined in D
as a OneToMany relationship (Many D
models to one A
model) with a resource_name on the ForeignKey declared in D
, and trying to reference this in C
to include that relationship in the JSON doesn't work, either.
Any help would be greatly appreciated.
Aucun commentaire:
Enregistrer un commentaire