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
python django serialization django-rest-framework


source to share


No one has answered this question yet

Check out similar questions:

1185
JSON serialization in jQuery
five
django - inlineformset_factory with multiple foreign keys
4
Radio buttons in django admin
3
Serializing a custom field to DRF
3
Django-Rest-Framework - how to serialize a request from an unbound model as a nested serializer
1
Product catalog: filter by parameters
1
Create a new model that contains all the fields of the existing model
1
How to define mode with regular ForeignKey in Django
1
Show subclass information in django display_list
0
How to implement update_or_create inside ModelSerializer create method



All Articles
Loading...
X
Show
Funny
Dev
Pics