Skip to content

Commit df6ca51

Browse files
committed
made MongoAutoField.get_prep_value() accept ObjectId strings
1 parent 67c70ab commit df6ca51

File tree

2 files changed

+11
-11
lines changed

2 files changed

+11
-11
lines changed

django_mongodb/features.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):
6161
"aggregation.tests.AggregateTestCase.test_aggregation_default_passed_another_aggregate",
6262
"aggregation.tests.AggregateTestCase.test_annotation_expressions",
6363
"aggregation.tests.AggregateTestCase.test_reverse_fkey_annotate",
64-
# MongoAutoField.get_prep_value() must accept strings.
65-
"model_forms.test_modelchoicefield.ModelChoiceFieldTests.test_choices",
66-
"model_forms.test_modelchoicefield.ModelChoiceFieldTests.test_clean_model_instance",
67-
"model_forms.tests.ModelFormBasicTests.test_m2m_editing",
68-
"model_forms.tests.ModelMultipleChoiceFieldTests.test_clean_does_deduplicate_values",
69-
"model_forms.tests.ModelMultipleChoiceFieldTests.test_model_multiple_choice_field",
70-
"model_forms.tests.ModelOneToOneFieldTests.test_onetoonefield",
71-
"model_forms.tests.ModelFormBasicTests.test_initial_values",
72-
"model_forms.tests.ModelMultipleChoiceFieldTests.test_model_multiple_choice_show_hidden_initial",
7364
# AutoField (IntegerField) validators crash MongoAutoField.
7465
"model_forms.tests.ModelFormBasicTests.test_recleaning_model_form_instance",
7566
}

django_mongodb/fields/auto.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,17 @@ def __init__(self, *args, **kwargs):
1515
super().__init__(*args, **kwargs)
1616

1717
def get_prep_value(self, value):
18-
# Override AutoField casting to integer.
19-
return Field.get_prep_value(self, value)
18+
if value is None:
19+
return None
20+
# Accept int for compatibility with Django's test suite which has many
21+
# instances of manually assigned integer IDs, as well as for things
22+
# like settings.SITE_ID which has a system check requiring an integer.
23+
if isinstance(value, (ObjectId | int)):
24+
return value
25+
try:
26+
return ObjectId(value)
27+
except errors.InvalidId as e:
28+
raise ValueError(f"Field '{self.name}' expected an ObjectId but got {value!r}.") from e
2029

2130
def rel_db_type(self, connection):
2231
return Field().db_type(connection=connection)

0 commit comments

Comments
 (0)