A reference to *any* :class:`~mongoengine.document.Document` subclass. Unlike the :class:`~mongoengine.fields.GenericReferenceField` it will **not** be automatically (lazily) dereferenced on access. Instead, access will return a :class:`~mongoengine.base.LazyReference` class instance
| 2552 | |
| 2553 | |
| 2554 | class GenericLazyReferenceField(GenericReferenceField): |
| 2555 | """A reference to *any* :class:`~mongoengine.document.Document` subclass. |
| 2556 | Unlike the :class:`~mongoengine.fields.GenericReferenceField` it will |
| 2557 | **not** be automatically (lazily) dereferenced on access. |
| 2558 | Instead, access will return a :class:`~mongoengine.base.LazyReference` class |
| 2559 | instance, allowing access to `pk` or manual dereference by using |
| 2560 | ``fetch()`` method. |
| 2561 | |
| 2562 | .. note :: |
| 2563 | * Any documents used as a generic reference must be registered in the |
| 2564 | document registry. Importing the model will automatically register |
| 2565 | it. |
| 2566 | |
| 2567 | * You can use the choices param to limit the acceptable Document types |
| 2568 | """ |
| 2569 | |
| 2570 | def __init__(self, *args, **kwargs): |
| 2571 | self.passthrough = kwargs.pop("passthrough", False) |
| 2572 | super().__init__(*args, **kwargs) |
| 2573 | |
| 2574 | def _validate_choices(self, value): |
| 2575 | if isinstance(value, LazyReference): |
| 2576 | value = value.document_type._class_name |
| 2577 | super()._validate_choices(value) |
| 2578 | |
| 2579 | def build_lazyref(self, value): |
| 2580 | if isinstance(value, LazyReference): |
| 2581 | if value.passthrough != self.passthrough: |
| 2582 | value = LazyReference( |
| 2583 | value.document_type, value.pk, passthrough=self.passthrough |
| 2584 | ) |
| 2585 | elif value is not None: |
| 2586 | if isinstance(value, (dict, SON)): |
| 2587 | value = LazyReference( |
| 2588 | get_document(value["_cls"]), |
| 2589 | value["_ref"].id, |
| 2590 | passthrough=self.passthrough, |
| 2591 | ) |
| 2592 | elif isinstance(value, Document): |
| 2593 | value = LazyReference( |
| 2594 | type(value), value.pk, passthrough=self.passthrough |
| 2595 | ) |
| 2596 | return value |
| 2597 | |
| 2598 | def __get__(self, instance, owner): |
| 2599 | if instance is None: |
| 2600 | return self |
| 2601 | |
| 2602 | value = self.build_lazyref(instance._data.get(self.name)) |
| 2603 | if value: |
| 2604 | instance._data[self.name] = value |
| 2605 | |
| 2606 | return super().__get__(instance, owner) |
| 2607 | |
| 2608 | def validate(self, value): |
| 2609 | if isinstance(value, LazyReference) and value.pk is None: |
| 2610 | self.error( |
| 2611 | "You can only reference documents once they have been" |
no outgoing calls
no test coverage detected