Serializing a recursive ManyToMany model in Django

I am writing a REST API for my Django application and I am having trouble serializing many-to-many recursive relationships. I found some help online, but this all seems to only apply to recursive many-to-many relationships without the model specified through

.

My models look like this:

class Place(models.Model):
    name = models.CharField(max_length=60)

    other_places = models.ManyToManyField('self', through='PlaceToPlace', symmetrical=False)

    def __str__(self):
        return self.name


class PlaceToPlace(models.Model):
    travel_time = models.BigIntegerField()
    origin_place = models.ForeignKey(Place, related_name="destination_places")
    destination_place = models.ForeignKey(Place, related_name="origin_places")

      

And I tried writing this serializer:

class PlaceToPlaceSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.Field(source='destination_places.id')
    name = serializers.Field(source='destination_places.name')

    class Meta:
        model = PlaceToPlace
        fields = ('id', 'name', 'travel_time')


class PlaceFullSerializer(serializers.ModelSerializer):
    class Meta:
        model = Place
        fields = ('id', 'name')

      

And so I need to write something to serialize related instances Place

, so I would end up with something like this:

[
    {
        "id": 1, 
        "name": "Place 1",
        "places":
        [
            {
                "id": 2, 
                "name": "Place 2",
                "travel_time": 300
            }
        ]
    }, 
    {
        "id": 2, 
        "name": "Place 2",
        "places":
        [
            {
                "id": 1, 
                "name": "Place 1",
                "travel_time": 300
            }
        ]
    }
]

      

But I can't figure out how to write a serializer, so some help would be much appreciated.

+3


source to share





All Articles