django-rest-framework-bulk icon indicating copy to clipboard operation
django-rest-framework-bulk copied to clipboard

compatibility with mongodb (specifically with https://github.com/umutbozkurt/django-rest-framework-mongoengine)

Open Jcbobo opened this issue 10 years ago • 0 comments

The update method of a bulkSerializer is not working if the id is not of type string/unicode for example a bson.objectid.ObjectId

mine solution was to force the unicode type in the BulkListSerializer

class BulkListSerializer(ListSerializer): update_lookup_field = 'id'

def update(self, queryset, all_validated_data):
    id_attr = getattr(self.child.Meta, 'update_lookup_field', 'id')
    all_validated_data_by_id = {
        i.pop(id_attr): i
        for i in all_validated_data
    }

    if not all((bool(i) and not inspect.isclass(i)
                for i in all_validated_data_by_id.keys())):
        raise ValidationError('')

    # since this method is given a queryset which can have many
    # model instances, first find all objects to update
    # and only then update the models
    objects_to_update = queryset.filter(**{
        '{}__in'.format(id_attr): all_validated_data_by_id.keys(),
    })

    if len(all_validated_data_by_id) != objects_to_update.count():
        raise ValidationError('Could not find all objects to update.')

    updated_objects = []
    for obj in objects_to_update:
        obj_id = getattr(obj, id_attr)
        #here
        obj_validated_data = all_validated_data_by_id.get(unicode(obj_id))
        # use model serializer to actually update the model
        # in case that method is overwritten
        updated_objects.append(self.child.update(obj, obj_validated_data))

    return updated_objects

I think is not a "portable solution" but make the job for me.

Jcbobo avatar Nov 16 '15 09:11 Jcbobo