Skip to content

Commit 03f186f

Browse files
committed
ObjectIdField does not support int or invalid strings.
1 parent 785bcfe commit 03f186f

File tree

2 files changed

+29
-15
lines changed

2 files changed

+29
-15
lines changed

django_mongodb/fields/auto.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from bson import ObjectId, errors
2+
from django.core import exceptions
13
from django.db.models.fields import AutoField
24
from django.utils.functional import cached_property
35

@@ -20,6 +22,21 @@ def deconstruct(self):
2022
def get_internal_type(self):
2123
return "ObjectIdAutoField"
2224

25+
def to_python(self, value):
26+
if value is None or isinstance(value, int):
27+
return value
28+
try:
29+
return ObjectId(value)
30+
except (errors.InvalidId, TypeError):
31+
try:
32+
return int(value)
33+
except (ValueError, TypeError):
34+
raise exceptions.ValidationError(
35+
self.error_messages["invalid"],
36+
code="invalid",
37+
params={"value": value},
38+
) from None
39+
2340
@cached_property
2441
def validators(self):
2542
# Avoid IntegerField validators inherited from AutoField.

django_mongodb/fields/objectid.py

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,21 +32,6 @@ def get_prep_value(self, value):
3232
def rel_db_type(self, connection):
3333
return "objectId"
3434

35-
def to_python(self, value):
36-
if value is None or isinstance(value, int):
37-
return value
38-
try:
39-
return ObjectId(value)
40-
except (errors.InvalidId, TypeError):
41-
try:
42-
return int(value)
43-
except (ValueError, TypeError):
44-
raise exceptions.ValidationError(
45-
self.error_messages["invalid"],
46-
code="invalid",
47-
params={"value": value},
48-
) from None
49-
5035

5136
class ObjectIdField(ObjectIdMixin, Field):
5237
def get_internal_type(self):
@@ -57,3 +42,15 @@ def deconstruct(self):
5742
if path.startswith("django_mongodb.fields.objectid"):
5843
path = path.replace("django_mongodb.fields.objectid", "django_mongodb.fields")
5944
return name, path, args, kwargs
45+
46+
def to_python(self, value):
47+
if value is None:
48+
return value
49+
try:
50+
return ObjectId(value)
51+
except (errors.InvalidId, TypeError):
52+
raise exceptions.ValidationError(
53+
self.error_messages["invalid"],
54+
code="invalid",
55+
params={"value": value},
56+
) from None

0 commit comments

Comments
 (0)