Skip to content

Commit 8f4c8e9

Browse files
committed
make MongoAutoField.get_prep_value() accept ObjectId strings
1 parent 0b511f4 commit 8f4c8e9

File tree

2 files changed

+12
-11
lines changed

2 files changed

+12
-11
lines changed

django_mongodb/features.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -69,16 +69,8 @@ class DatabaseFeatures(BaseDatabaseFeatures):
6969
"aggregation_regress.tests.AggregationTests.test_more_more_more3",
7070
# Incorrect JOIN with GenericRelation gives incorrect results.
7171
"aggregation_regress.tests.AggregationTests.test_aggregation_with_generic_reverse_relation",
72-
# MongoAutoField.get_prep_value() must accept strings.
73-
"model_forms.test_modelchoicefield.ModelChoiceFieldTests.test_choices",
74-
"model_forms.test_modelchoicefield.ModelChoiceFieldTests.test_clean_model_instance",
72+
# MongoAutoField.get_prep_value() must accept numeric pks.
7573
"model_forms.tests.ModelFormBasicTests.test_int_pks",
76-
"model_forms.tests.ModelFormBasicTests.test_m2m_editing",
77-
"model_forms.tests.ModelMultipleChoiceFieldTests.test_clean_does_deduplicate_values",
78-
"model_forms.tests.ModelMultipleChoiceFieldTests.test_model_multiple_choice_field",
79-
"model_forms.tests.ModelOneToOneFieldTests.test_onetoonefield",
80-
"model_forms.tests.ModelFormBasicTests.test_initial_values",
81-
"model_forms.tests.ModelMultipleChoiceFieldTests.test_model_multiple_choice_show_hidden_initial",
8274
# AutoField (IntegerField) validators crash MongoAutoField.
8375
"model_forms.tests.ModelFormBasicTests.test_recleaning_model_form_instance",
8476
}

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)