|
| 1 | +from bson import ObjectId, errors |
| 2 | +from django.core import exceptions |
| 3 | +from django.db.models.fields import Field |
| 4 | +from django.utils.translation import gettext_lazy as _ |
| 5 | + |
| 6 | +from django_mongodb import forms |
| 7 | + |
| 8 | + |
| 9 | +class ObjectIdMixin: |
| 10 | + default_error_messages = { |
| 11 | + "invalid": _("“%(value)s” is not a valid Object Id."), |
| 12 | + } |
| 13 | + description = _("Object Id") |
| 14 | + |
| 15 | + def db_type(self, connection): |
| 16 | + return "objectId" |
| 17 | + |
| 18 | + def rel_db_type(self, connection): |
| 19 | + return "objectId" |
| 20 | + |
| 21 | + def get_prep_value(self, value): |
| 22 | + value = super().get_prep_value(value) |
| 23 | + return self.to_python(value) |
| 24 | + |
| 25 | + def to_python(self, value): |
| 26 | + if value is None: |
| 27 | + return value |
| 28 | + try: |
| 29 | + return ObjectId(value) |
| 30 | + except (errors.InvalidId, TypeError): |
| 31 | + raise exceptions.ValidationError( |
| 32 | + self.error_messages["invalid"], |
| 33 | + code="invalid", |
| 34 | + params={"value": value}, |
| 35 | + ) from None |
| 36 | + |
| 37 | + def formfield(self, **kwargs): |
| 38 | + return super().formfield( |
| 39 | + **{ |
| 40 | + "form_class": forms.ObjectIdField, |
| 41 | + **kwargs, |
| 42 | + } |
| 43 | + ) |
| 44 | + |
| 45 | + |
| 46 | +class ObjectIdField(ObjectIdMixin, Field): |
| 47 | + def deconstruct(self): |
| 48 | + name, path, args, kwargs = super().deconstruct() |
| 49 | + if path.startswith("django_mongodb.fields.objectid"): |
| 50 | + path = path.replace("django_mongodb.fields.objectid", "django_mongodb.fields") |
| 51 | + return name, path, args, kwargs |
| 52 | + |
| 53 | + def get_internal_type(self): |
| 54 | + return "ObjectIdField" |
0 commit comments