Skip to content

Commit 2a59bdc

Browse files
committed
Add get_prep_value.
1 parent 3e817db commit 2a59bdc

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

django_mongodb/fields/objectid.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from bson import ObjectId
1+
from bson import ObjectId, errors
22
from bson.errors import InvalidId
33
from django.core import exceptions
44
from django.db.models.fields import Field
@@ -34,6 +34,14 @@ def to_python(self, value):
3434
params={"value": value},
3535
) from None
3636

37+
def get_prep_value(self, value):
38+
if value is None:
39+
return None
40+
try:
41+
return ObjectId(value)
42+
except (errors.InvalidId, TypeError) as e:
43+
raise ValueError(f"Field '{self.name}' expected an ObjectId but got {value!r}.") from e
44+
3745
def deconstruct(self):
3846
name, path, args, kwargs = super().deconstruct()
3947
if path.startswith("django_mongodb.fields.objectid"):

0 commit comments

Comments
 (0)