Skip to content

Commit

Permalink
prohibit int in ObjectIdAutoField
Browse files Browse the repository at this point in the history
  • Loading branch information
timgraham committed Feb 11, 2025
1 parent eb26848 commit c280480
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 20 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/test-python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ jobs:
- name: Checkout Django
uses: actions/checkout@v4
with:
repository: 'mongodb-forks/django'
ref: 'mongodb-5.1.x'
repository: 'timgraham/django'
ref: 'objectid-no-int'
path: 'django_repo'
persist-credentials: false
- name: Install system packages for Django's Python test dependencies
Expand Down
23 changes: 6 additions & 17 deletions django_mongodb_backend/fields/auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,11 @@ def deconstruct(self):
return name, path, args, kwargs

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

def get_internal_type(self):
Expand All @@ -46,14 +38,11 @@ def to_python(self, value):
try:
return ObjectId(value)
except errors.InvalidId:
try:
return int(value)
except ValueError:
raise exceptions.ValidationError(
self.error_messages["invalid"],
code="invalid",
params={"value": value},
) from None
raise exceptions.ValidationError(
self.error_messages["invalid"],
code="invalid",
params={"value": value},
) from None

@cached_property
def validators(self):
Expand Down
5 changes: 4 additions & 1 deletion tests/model_fields_/test_autofield.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.core.exceptions import ValidationError
from django.test import SimpleTestCase

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

def test_to_python(self):
f = ObjectIdAutoField()
self.assertEqual(f.to_python("1"), 1)
msg = "“1” is not a valid Object Id."
with self.assertRaisesMessage(ValidationError, msg):
f.to_python("1")

0 comments on commit c280480

Please sign in to comment.