djangomongodbmongoenginerestframeworkmongoengine

MapField is not displayed in Django Rest Framework Mongoengine


I have a model with following attributes.

class File(DynamicDocument):
    country = fields.StringField(max_length=100, unique=True)
    languages = fields.MapField(fields.MapField(
        fields.EmbeddedDocumentField(AudioImage)))

I am trying to use Django Rest Framework Mongoengine as follows:

from rest_framework_mongoengine.serializers import DocumentSerializer

class TestSerializer(DocumentSerializer):
    class Meta:
        model = File

It simply gives the following output:

enter image description here

But I wanted it to address the tree like structure with all the fields from AudioImage class as well. Did I miss anything? or There is another way for MapField ?


Solution

  • Sijan, is it correct that you want your File documents to have the following structure:

    {
        "country": "UK",
        "languages": {
            "hindi": AudioImageJSON,
            "russian": AudioImageJSON,
            "cockney": AudioImageJSON
        }
    }
    

    where the structure of AudioImageJSON is described by corresponding EmbeddedDocument?

    In that case, your DocumentSerializer is correct and your specify your model as follows:

    class AudioImage(EmbeddedDocument):
        content = fields.FileField()
    
    class File(DynamicDocument):
        country = fields.StringField(max_length=100, unique=True)
        languages = fields.MapField(fields.EmbeddedDocumentField(AudioImage))
    

    Note that Browsable API won't be able to display nested form inputs for EmbeddedDocument fields. But you may still use raw data view.