简体   繁体   中英

Django REST - How can I get a JSON with two models?

I've two models (Map and Place) and I want to create a JSON with both of these (a map contains several places).

models.py

class Map(models.Model):
   name = models.CharField(max_length=100)
   slug = models.SlugField(max_length=200)

class Place(models.Model):
   map = models.ForeignKey('main.Map')
   name = models.CharField(max_length=100)
   slug = models.SlugField(max_length=200)

I use this to serialize these models individually :

serializers.py

class MapSerializer(serializers.ModelSerializer):
    class Meta:
        model = Map
        fields = ('id', 'name')

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

I want a JSON like this, but I've no idea how to serialize this correctly...

{
    "maplist": {
        "maps": [
            {
                "id": "1",
                "name": "dust2",
                "places": [
                    {
                        "id": "1",
                        "name": "Long"
                    },
                    {
                        "id": "2",
                        "name": "Middle"
                    }
                ]
            },
            {
                "id": "2",
                "name": "inferno",
                "places": [
                    {
                        "id": "1",
                        "name": "Middle"
                    },
                    {
                        "id": "2",
                        "name": "ASite"
                    }
                ]
            }


        ]
    }
}

Thanks in advance for your help.

Try with nested serializers:

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

class MapSerializer(serializers.ModelSerializer):
    places = PlaceSerializer(many=True)
    class Meta:
        model = Map
        fields = ('id', 'name')

To make this work, you need to change your model to include a related name to your foreign key:

class Place(models.Model):
   map = models.ForeignKey('main.Map', related_name="places")
   name = models.CharField(max_length=100)
   slug = models.SlugField(max_length=200)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM