|
| 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