Skip to content

Commit 68c026b

Browse files
committed
prohibit int in ObjectIdAutoField
1 parent eb26848 commit 68c026b

File tree

3 files changed

+12
-20
lines changed

3 files changed

+12
-20
lines changed

.github/workflows/test-python.yml

+2-2
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ jobs:
3232
- name: Checkout Django
3333
uses: actions/checkout@v4
3434
with:
35-
repository: 'mongodb-forks/django'
36-
ref: 'mongodb-5.1.x'
35+
repository: 'timgraham/django'
36+
ref: 'objectid-no-int'
3737
path: 'django_repo'
3838
persist-credentials: false
3939
- name: Install system packages for Django's Python test dependencies

django_mongodb_backend/fields/auto.py

+6-17
Original file line numberDiff line numberDiff line change
@@ -22,19 +22,11 @@ def deconstruct(self):
2222
return name, path, args, kwargs
2323

2424
def get_prep_value(self, value):
25-
if value is None:
26-
return None
27-
# Accept int for compatibility with Django's test suite which has many
28-
# instances of manually assigned integer IDs, as well as for things
29-
# like settings.SITE_ID which has a system check requiring an integer.
30-
if isinstance(value, (ObjectId | int)):
25+
if value is None or isinstance(value, ObjectId):
3126
return value
3227
try:
3328
return ObjectId(value)
3429
except errors.InvalidId as e:
35-
# A manually assigned integer ID?
36-
if isinstance(value, str) and value.isdigit():
37-
return int(value)
3830
raise ValueError(f"Field '{self.name}' expected an ObjectId but got {value!r}.") from e
3931

4032
def get_internal_type(self):
@@ -46,14 +38,11 @@ def to_python(self, value):
4638
try:
4739
return ObjectId(value)
4840
except errors.InvalidId:
49-
try:
50-
return int(value)
51-
except ValueError:
52-
raise exceptions.ValidationError(
53-
self.error_messages["invalid"],
54-
code="invalid",
55-
params={"value": value},
56-
) from None
41+
raise exceptions.ValidationError(
42+
self.error_messages["invalid"],
43+
code="invalid",
44+
params={"value": value},
45+
) from None
5746

5847
@cached_property
5948
def validators(self):

tests/model_fields_/test_autofield.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from django.core.exceptions import ValidationError
12
from django.test import SimpleTestCase
23

34
from django_mongodb_backend.fields import ObjectIdAutoField
@@ -17,4 +18,6 @@ def test_get_internal_type(self):
1718

1819
def test_to_python(self):
1920
f = ObjectIdAutoField()
20-
self.assertEqual(f.to_python("1"), 1)
21+
msg = "“1” is not a valid Object Id."
22+
with self.assertRaisesMessage(ValidationError, msg):
23+
f.to_python("1")

0 commit comments

Comments
 (0)