I am try to create a simple model that is referred to itself through an intermediate table. Below the code.
class Entity(models.Model):
.....
childs = models.ManyToManyField(
to='Entity',
symmetrical=False,
related_name='from_entities',
verbose_name='Child Entities',
through='EntityChild',
through_fields=('from_entity', 'to_entity'))
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'entity'
verbose_name_plural = 'Entities'
The intermediate table below
class EntityChild(models.Model):
from_entity = models.ForeignKey(
Entity, on_delete=models.RESTRICT, related_name='from_entity')
to_entity = models.ForeignKey(
Entity, on_delete=models.RESTRICT, related_name='to_entity')
.....,
type = models.CharField(
max_length=255, verbose_name='Type')
class Meta:
db_table = 'entity_childs'
And the serializeres
class EntityChildSerializer(serializers.ModelSerializer):
to_entity = serializers.RelatedField(many=False, read_only=True)
def to_representation(self, value):
serializer = self.parent.parent.__class__(value, context=self.context)
class Meta:
model = EntityChild
fields = ('to_entity', 'type',....)
class EntitySerializer(serializers.ModelSerializer):
fields = FieldSerializer(many=True)
tags = TagSerializer(many=True)
childs = EntityChildSerializer(source='from_entity', many=True)
class Meta:
model = Entity
fields = ('id', 'childs', 'created_at', 'updated_at')
So at the end my entity child will have a relation ManyToMany with the EntityChild that hold a reference to another entity.
With the code below the serializer will return
{
"id": 1,
"childs": [
null
],...
}
I tried follow this Nested serializer "Through model" in Django Rest Framework with no luck.
Any help will be appreciated... Thank you all.