Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializer for mongodb default Object id with difference field name in Django rest framework?

I want to change objectId name from 'id' to 'user_id' at the time of parsing in response for django request. i am using django-rest-framework-mongoengine

My user serializer looks like this

class UserSerializer(DocumentSerializer):

    user_id = serializers.Field(source='id')
    class Meta:
        model = User
        depth = 2
        fields = ('user_id','name','address')
like image 841
Himanshu Jain Avatar asked Dec 11 '25 23:12

Himanshu Jain


1 Answers

You should define the field as:

from rest_framework_mongoengine.serializers import DocumentSerializer
from rest_framework_mongoengine.fields import ObjectIdField
from my_app.documents import User

class UserSerializer(DocumentSerializer):

    user_id = ObjectIdField(source='id')
    class Meta:
        model = User
        depth = 2
        fields = ('user_id','name','address')

The difference is that you should use the django-rest-framework-mongoengine's ObjectIdField.

like image 58
Wtower Avatar answered Dec 14 '25 18:12

Wtower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!