Skip to content

Instantly share code, notes, and snippets.

@mosi-kha
Created July 11, 2021 07:04
Show Gist options
  • Save mosi-kha/cff3ece506645746e3518a0aae076acb to your computer and use it in GitHub Desktop.
Save mosi-kha/cff3ece506645746e3518a0aae076acb to your computer and use it in GitHub Desktop.
MongoDB Object Id field for DRF serializer
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