Skip to content

Commit f6f3d70

Browse files
committed
Add ObjectIdField.
1 parent 05d9914 commit f6f3d70

File tree

3 files changed

+39
-5
lines changed

3 files changed

+39
-5
lines changed

django_mongodb/features.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,10 +78,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):
7878
"queries.test_qs_combinators.QuerySetSetOperationTests.test_union_in_subquery_related_outerref",
7979
"queries.test_qs_combinators.QuerySetSetOperationTests.test_union_in_subquery",
8080
"queries.test_qs_combinators.QuerySetSetOperationTests.test_union_in_with_ordering",
81-
# ObjectId type mismatch in a subquery:
82-
# https://github.com/mongodb-labs/django-mongodb/issues/161
83-
"queries.tests.RelatedLookupTypeTests.test_values_queryset_lookup",
84-
"queries.tests.ValuesSubqueryTests.test_values_in_subquery",
8581
# Object of type ObjectId is not JSON serializable.
8682
"auth_tests.test_views.LoginTest.test_login_session_without_hash_session_key",
8783
# GenericRelation.value_to_string() assumes integer pk.

django_mongodb/fields/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
from .auto import ObjectIdAutoField
22
from .duration import register_duration_field
33
from .json import register_json_field
4+
from .object_id import ObjectIdField
45

5-
__all__ = ["register_fields", "ObjectIdAutoField"]
6+
__all__ = ["register_fields", "ObjectIdAutoField", "ObjectIdField"]
67

78

89
def register_fields():

django_mongodb/fields/object_id.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from bson import ObjectId
2+
from bson.errors import InvalidId
3+
from django.core import exceptions
4+
from django.db.models.fields import Field
5+
from django.utils.translation import gettext_lazy as _
6+
7+
8+
class ObjectIdField(Field):
9+
default_error_messages = {
10+
"invalid": _("“%(value)s” value must be an Object Id."),
11+
}
12+
description = _("ObjectId")
13+
14+
def get_internal_type(self):
15+
return "ObjectIdField"
16+
17+
def db_type(self, connection):
18+
return "objectId"
19+
20+
def rel_db_type(self, connection):
21+
return "objectId"
22+
23+
def to_python(self, value):
24+
try:
25+
return ObjectId(value)
26+
except (TypeError, InvalidId):
27+
raise exceptions.ValidationError(
28+
self.error_messages["invalid"],
29+
code="invalid",
30+
params={"value": value},
31+
) from None
32+
33+
def deconstruct(self):
34+
name, path, args, kwargs = super().deconstruct()
35+
if path.startswith("django_mongodb.fields.auto"):
36+
path = path.replace("django_mongodb.fields.auto", "django_mongodb.fields")
37+
return name, path, args, kwargs

0 commit comments

Comments
 (0)