A really lazy reference to a document. Unlike the :class:`~mongoengine.fields.ReferenceField` it will **not** be automatically (lazily) dereferenced on access. Instead, access will return a :class:`~mongoengine.base.LazyReference` class instance, allowing access to `pk` or manual der
| 2396 | |
| 2397 | |
| 2398 | class LazyReferenceField(BaseField): |
| 2399 | """A really lazy reference to a document. |
| 2400 | Unlike the :class:`~mongoengine.fields.ReferenceField` it will |
| 2401 | **not** be automatically (lazily) dereferenced on access. |
| 2402 | Instead, access will return a :class:`~mongoengine.base.LazyReference` class |
| 2403 | instance, allowing access to `pk` or manual dereference by using |
| 2404 | ``fetch()`` method. |
| 2405 | """ |
| 2406 | |
| 2407 | def __init__( |
| 2408 | self, |
| 2409 | document_type, |
| 2410 | passthrough=False, |
| 2411 | dbref=False, |
| 2412 | reverse_delete_rule=DO_NOTHING, |
| 2413 | **kwargs, |
| 2414 | ): |
| 2415 | """Initialises the Reference Field. |
| 2416 | |
| 2417 | :param dbref: Store the reference as :class:`~pymongo.dbref.DBRef` |
| 2418 | or as the :class:`~pymongo.objectid.ObjectId`.id . |
| 2419 | :param reverse_delete_rule: Determines what to do when the referring |
| 2420 | object is deleted |
| 2421 | :param passthrough: When trying to access unknown fields, the |
| 2422 | :class:`~mongoengine.base.datastructure.LazyReference` instance will |
| 2423 | automatically call `fetch()` and try to retrieve the field on the fetched |
| 2424 | document. Note this only work getting field (not setting or deleting). |
| 2425 | """ |
| 2426 | # XXX ValidationError raised outside of the "validate" method. |
| 2427 | if not isinstance(document_type, str) and not issubclass( |
| 2428 | document_type, Document |
| 2429 | ): |
| 2430 | self.error( |
| 2431 | "Argument to LazyReferenceField constructor must be a " |
| 2432 | "document class or a string" |
| 2433 | ) |
| 2434 | |
| 2435 | self.dbref = dbref |
| 2436 | self.passthrough = passthrough |
| 2437 | self.document_type_obj = document_type |
| 2438 | self.reverse_delete_rule = reverse_delete_rule |
| 2439 | super().__init__(**kwargs) |
| 2440 | |
| 2441 | @property |
| 2442 | def document_type(self): |
| 2443 | if isinstance(self.document_type_obj, str): |
| 2444 | if self.document_type_obj == RECURSIVE_REFERENCE_CONSTANT: |
| 2445 | self.document_type_obj = self.owner_document |
| 2446 | else: |
| 2447 | self.document_type_obj = get_document(self.document_type_obj) |
| 2448 | return self.document_type_obj |
| 2449 | |
| 2450 | def build_lazyref(self, value): |
| 2451 | if isinstance(value, LazyReference): |
| 2452 | if value.passthrough != self.passthrough: |
| 2453 | value = LazyReference( |
| 2454 | value.document_type, value.pk, passthrough=self.passthrough |
| 2455 | ) |
no outgoing calls