djongo icon indicating copy to clipboard operation
djongo copied to clipboard

django rest framework and embedded EmbeddedModelField

Open MiltosD opened this issue 8 years ago • 14 comments

I really like the feature that making a model abstract we can avoid creating separate collections, since it makes sense to me to create collections for reusable documents only. However, I've been having a hard time trying to serialize those models with DRF. Is there any specific documentation on the matter?

MiltosD avatar Apr 19 '18 15:04 MiltosD

Lets say your models look like this:

class MyEmbeddedModel(models.Model):

    ...

    class Meta:
        abstract = True

class MyModel(models.Model):
    
    my_embedded_model = models.EmbeddedModelField(model=MyEmbeddedModel)

    objects = models.DjongoManager()


(or something like that)

Then you can do:


from bson.json_util import dumps

# MyModel is the parent

@api_view(['GET'])
def my_view(request): 
    query = MyModel.objects.mongo_find()
    return dumps(query)

This should be a really fast, because you're using the native converter. It's at least my solution to the problem.

halvorboe avatar Apr 20 '18 07:04 halvorboe

Thank you very much!

MiltosD avatar Apr 21 '18 10:04 MiltosD

@MiltosD This is how I use Djongo with DRF - This handles both EmbeddedModelFields and ArrayModelFields. Define a serializer for the model with the embedded field in the following way:

# Let's say the name of the embedded field in the ParentModel is "embedded_field"
class SampleSerializer(serializers.ModelSerializer):
    # You need to define a SerializerMethodField for every embedded model field in the ParentModel
    embedded_field = serializers.SerializerMethodField()
    class Meta:
        model = ParentModel
        fields = ('id', 'title', 'embedded_field')

    def get_embedded_field(self, obj):
        return_data = None
        if type(obj.embedded_field) == list:
            embedded_list = []
            for item in field:
                embedded_dict = item.__dict__
                for key in list(embedded_dict.keys()):
                    if key.startswith('_'):
                        embedded_dict.pop(key)
                embedded_list.append(embedded_dict)
            return_data = embedded_list
        else:
            embedded_dict = field.__dict__
            for key in list(embedded_dict.keys()):
                if key.startswith('_'):
                    embedded_dict.pop(key)
            return_data = embedded_dict
        return return_data

arindammanidas avatar Apr 27 '18 09:04 arindammanidas

field in field.__dict__ is actually obj.embedded_field for those that might be confused with @arindammanidas' solution.

ren477a avatar May 17 '18 14:05 ren477a

@arindammanidas: Great!!

ibrahimsha23 avatar Dec 16 '18 05:12 ibrahimsha23

Thank you for this post. Helped me get over the issue!

msagar1 avatar Jul 15 '19 12:07 msagar1

@MiltosD This is how I use Djongo with DRF - This handles both EmbeddedModelFields and ArrayModelFields. Define a serializer for the model with the embedded field in the following way:

# Let's say the name of the embedded field in the ParentModel is "embedded_field"
class SampleSerializer(serializers.ModelSerializer):
    # You need to define a SerializerMethodField for every embedded model field in the ParentModel
    embedded_field = serializers.SerializerMethodField()
    class Meta:
        model = ParentModel
        fields = ('id', 'title', 'embedded_field')

    def get_embedded_field(self, obj):
        return_data = None
        if type(obj.embedded_field) == list:
            embedded_list = []
            for item in field:
                embedded_dict = item.__dict__
                for key in list(embedded_dict.keys()):
                    if key.startswith('_'):
                        embedded_dict.pop(key)
                embedded_list.append(embedded_dict)
            return_data = embedded_list
        else:
            embedded_dict = field.__dict__
            for key in list(embedded_dict.keys()):
                if key.startswith('_'):
                    embedded_dict.pop(key)
            return_data = embedded_dict
        return return_data

How to post data ?

saumyachoudhary31 avatar Jun 06 '20 13:06 saumyachoudhary31

@arindammanidas I am getting errror with this that 'NoneType' object has no attribute 'keys'

saumyachoudhary31 avatar Jun 07 '20 09:06 saumyachoudhary31

@MiltosD This is how I use Djongo with DRF - This handles both EmbeddedModelFields and ArrayModelFields. Define a serializer for the model with the embedded field in the following way:

# Let's say the name of the embedded field in the ParentModel is "embedded_field"
class SampleSerializer(serializers.ModelSerializer):
    # You need to define a SerializerMethodField for every embedded model field in the ParentModel
    embedded_field = serializers.SerializerMethodField()
    class Meta:
        model = ParentModel
        fields = ('id', 'title', 'embedded_field')

    def get_embedded_field(self, obj):
        return_data = None
        if type(obj.embedded_field) == list:
            embedded_list = []
            for item in field:
                embedded_dict = item.__dict__
                for key in list(embedded_dict.keys()):
                    if key.startswith('_'):
                        embedded_dict.pop(key)
                embedded_list.append(embedded_dict)
            return_data = embedded_list
        else:
            embedded_dict = field.__dict__
            for key in list(embedded_dict.keys()):
                if key.startswith('_'):
                    embedded_dict.pop(key)
            return_data = embedded_dict
        return return_data

With above solution also im getting an error when i try to create model with Embeddedfields within it from django Admin. Says the EmbeddedFiled should be a instance of dict. "Value: Design must be an instance of <class 'dict'>"

sampathkr1212 avatar Aug 03 '20 17:08 sampathkr1212

@MiltosD This is how I use Djongo with DRF - This handles both EmbeddedModelFields and ArrayModelFields. Define a serializer for the model with the embedded field in the following way:

# Let's say the name of the embedded field in the ParentModel is "embedded_field"
class SampleSerializer(serializers.ModelSerializer):
    # You need to define a SerializerMethodField for every embedded model field in the ParentModel
    embedded_field = serializers.SerializerMethodField()
    class Meta:
        model = ParentModel
        fields = ('id', 'title', 'embedded_field')

    def get_embedded_field(self, obj):
        return_data = None
        if type(obj.embedded_field) == list:
            embedded_list = []
            for item in field:
                embedded_dict = item.__dict__
                for key in list(embedded_dict.keys()):
                    if key.startswith('_'):
                        embedded_dict.pop(key)
                embedded_list.append(embedded_dict)
            return_data = embedded_list
        else:
            embedded_dict = field.__dict__
            for key in list(embedded_dict.keys()):
                if key.startswith('_'):
                    embedded_dict.pop(key)
            return_data = embedded_dict
        return return_data

With above solution also im getting an error when i try to create model with Embeddedfields within it from django Admin. Says the EmbeddedFiled should be a instance of dict. "Value: Design must be an instance of <class 'dict'>"

how to fix this

rainleon avatar Sep 01 '20 02:09 rainleon

Same error

@MiltosD This is how I use Djongo with DRF - This handles both EmbeddedModelFields and ArrayModelFields. Define a serializer for the model with the embedded field in the following way:

# Let's say the name of the embedded field in the ParentModel is "embedded_field"
class SampleSerializer(serializers.ModelSerializer):
    # You need to define a SerializerMethodField for every embedded model field in the ParentModel
    embedded_field = serializers.SerializerMethodField()
    class Meta:
        model = ParentModel
        fields = ('id', 'title', 'embedded_field')

    def get_embedded_field(self, obj):
        return_data = None
        if type(obj.embedded_field) == list:
            embedded_list = []
            for item in field:
                embedded_dict = item.__dict__
                for key in list(embedded_dict.keys()):
                    if key.startswith('_'):
                        embedded_dict.pop(key)
                embedded_list.append(embedded_dict)
            return_data = embedded_list
        else:
            embedded_dict = field.__dict__
            for key in list(embedded_dict.keys()):
                if key.startswith('_'):
                    embedded_dict.pop(key)
            return_data = embedded_dict
        return return_data

With above solution also im getting an error when i try to create model with Embeddedfields within it from django Admin. Says the EmbeddedFiled should be a instance of dict. "Value: Design must be an instance of <class 'dict'>"

how to fix this

I have this same issue , can someone help fixing it ?

4k45hv3rm4 avatar Oct 26 '20 12:10 4k45hv3rm4

@MiltosD This is how I use Djongo with DRF - This handles both EmbeddedModelFields and ArrayModelFields. Define a serializer for the model with the embedded field in the following way:

# Let's say the name of the embedded field in the ParentModel is "embedded_field"
class SampleSerializer(serializers.ModelSerializer):
    # You need to define a SerializerMethodField for every embedded model field in the ParentModel
    embedded_field = serializers.SerializerMethodField()
    class Meta:
        model = ParentModel
        fields = ('id', 'title', 'embedded_field')

    def get_embedded_field(self, obj):
        return_data = None
        if type(obj.embedded_field) == list:
            embedded_list = []
            for item in field:
                embedded_dict = item.__dict__
                for key in list(embedded_dict.keys()):
                    if key.startswith('_'):
                        embedded_dict.pop(key)
                embedded_list.append(embedded_dict)
            return_data = embedded_list
        else:
            embedded_dict = field.__dict__
            for key in list(embedded_dict.keys()):
                if key.startswith('_'):
                    embedded_dict.pop(key)
            return_data = embedded_dict
        return return_data

With above solution also im getting an error when i try to create model with Embeddedfields within it from django Admin. Says the EmbeddedFiled should be a instance of dict. "Value: Design must be an instance of <class 'dict'>"

Exactly same error here.

brunowego avatar Oct 30 '20 21:10 brunowego

Can you show the model clase code ? Embeded_field default value? Null =true?

El vie., 30 de oct. de 2020 6:10 p. m., Bruno Wego [email protected] escribió:

@MiltosD https://github.com/MiltosD This is how I use Djongo with DRF - This handles both EmbeddedModelFields and ArrayModelFields. Define a serializer for the model with the embedded field in the following way:

Let's say the name of the embedded field in the ParentModel is "embedded_field"

class SampleSerializer(serializers.ModelSerializer): # You need to define a SerializerMethodField for every embedded model field in the ParentModel embedded_field = serializers.SerializerMethodField() class Meta: model = ParentModel fields = ('id', 'title', 'embedded_field')

def get_embedded_field(self, obj):
    return_data = None
    if type(obj.embedded_field) == list:
        embedded_list = []
        for item in field:
            embedded_dict = item.__dict__
            for key in list(embedded_dict.keys()):
                if key.startswith('_'):
                    embedded_dict.pop(key)
            embedded_list.append(embedded_dict)
        return_data = embedded_list
    else:
        embedded_dict = field.__dict__
        for key in list(embedded_dict.keys()):
            if key.startswith('_'):
                embedded_dict.pop(key)
        return_data = embedded_dict
    return return_data

With above solution also im getting an error when i try to create model with Embeddedfields within it from django Admin. Says the EmbeddedFiled should be a instance of dict. "Value: Design must be an instance of <class 'dict'>"

Exactly same error here.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/nesdis/djongo/issues/115#issuecomment-719801242, or unsubscribe https://github.com/notifications/unsubscribe-auth/AL2EH6HXDPR4MG5LLHV63N3SNMTU5ANCNFSM4E3P3ZLA .

antonio-irarrazaval avatar Oct 30 '20 21:10 antonio-irarrazaval

@antonio-irarrazaval take a look https://github.com/nesdis/djongo/issues/491

brunowego avatar Oct 30 '20 21:10 brunowego