Created
July 11, 2021 07:04
-
-
Save mosi-kha/cff3ece506645746e3518a0aae076acb to your computer and use it in GitHub Desktop.
MongoDB Object Id field for DRF serializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from bson import ObjectId | |
from bson.errors import InvalidId | |
from django.utils.encoding import smart_str | |
from rest_framework import serializers | |
class ObjectIdField(serializers.Field): | |
"""Field for ObjectId values""" | |
def to_internal_value(self, value): | |
try: | |
return ObjectId(smart_str(value)) | |
except InvalidId: | |
raise serializers.ValidationError("'%s' is not a valid ObjectId" % value) | |
def to_representation(self, value): | |
return smart_str(value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment