1👍
The problem may be in your relations, not in your serializers. Foreign keys are one-to-many relations, which for your example models means:
foo2 can have only one foo1 object assigned, but many foo2 objects can have the same foo1 object assigned. Same goes between foo2 and foo3, foo3 and foo4 etc…
If this is what you want, you can have the API structured like this:
[
{
"id": 1,
"name": "test1",
"foo2": [
{
"id": 1,
"name": "test1",
"foo3": [
{
"id": 1,
"name": "test1",
"foo3": [
...
],
},
{...}
]
},
{...}
]
},
....
]
Simply set a related name on each of the relations (or use a default one, which will be the "slugified" model name where the relation is defined with _set
added at the end of it):
class foo2(models.Model):
name = models.CharField(max_length=100)
....
foo1 = models.ForeignKey(foo1, on_delete=models.SET_NULL, null=True, related_name="foo2s")
And use it in your serializers with that related name and many=True
:
class foo1Serializer(serializers.ModelSerializer):
foo2s = NestedFoo2Serializer(read_only=True, many=True)
class Meta:
model = foo1
fields = '__all__'
If you want have the exact API structure as you’ve proposed in your question, you have to either reverse the relations, so the relation from foo1
to foo2
is defined in foo1
, or use OneToOneField
instead, which will limit every foo2
model to have a unique foo1
model assigned to it.