[Django]-Serialize to json nested one-to-many (opposite of many to one)

5👍

You can try using django rest framework.

Define a model serializer for Module model and Version model:

class VersionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Version

class ModuleSerializer(serializers.ModelSerializer):
    versions = VersionSerializer(many=True)
    class Meta:
        model = Module
        fields = ('id', ..... , 'versions')

Now define your Install model serialiser:

class InstallSerializer(serializers.ModelSerializer):
    modules = ModuleSerializer(many=True)
    class Meta:
        model = Install
        fields = ('id', ..... , 'modules')

This will serialize install data with all modules for each install and also all versions for each of the modules in a install.

EDIT:

I forgot to mention this, the name of the field of the related model should be the same as the value of related_name in the foreign key field.

For example in the Module model:

class Module(Models.Model):
    install = models.ForeignKey(Install, related_name='modules')

Now you have to use ‘modules’ as the name of the field in the serializer.

Leave a comment