Reloads all attributes from the database. :param fields: (optional) args list of fields to reload :param max_depth: (optional) depth of dereferencing to follow
(self, *fields, **kwargs)
| 760 | return self |
| 761 | |
| 762 | def reload(self, *fields, **kwargs): |
| 763 | """Reloads all attributes from the database. |
| 764 | |
| 765 | :param fields: (optional) args list of fields to reload |
| 766 | :param max_depth: (optional) depth of dereferencing to follow |
| 767 | """ |
| 768 | max_depth = 1 |
| 769 | if fields and isinstance(fields[0], int): |
| 770 | max_depth = fields[0] |
| 771 | fields = fields[1:] |
| 772 | elif "max_depth" in kwargs: |
| 773 | max_depth = kwargs["max_depth"] |
| 774 | |
| 775 | if self.pk is None: |
| 776 | raise self.DoesNotExist("Document does not exist") |
| 777 | |
| 778 | obj = ( |
| 779 | self._qs.read_preference(ReadPreference.PRIMARY) |
| 780 | .filter(**self._object_key) |
| 781 | .only(*fields) |
| 782 | .limit(1) |
| 783 | .select_related(max_depth=max_depth) |
| 784 | ) |
| 785 | |
| 786 | if obj: |
| 787 | obj = obj[0] |
| 788 | else: |
| 789 | raise self.DoesNotExist("Document does not exist") |
| 790 | for field in obj._data: |
| 791 | if not fields or field in fields: |
| 792 | try: |
| 793 | setattr(self, field, self._reload(field, obj[field])) |
| 794 | except (KeyError, AttributeError): |
| 795 | try: |
| 796 | # If field is a special field, e.g. items is stored as _reserved_items, |
| 797 | # a KeyError is thrown. So try to retrieve the field from _data |
| 798 | setattr(self, field, self._reload(field, obj._data.get(field))) |
| 799 | except KeyError: |
| 800 | # If field is removed from the database while the object |
| 801 | # is in memory, a reload would cause a KeyError |
| 802 | # i.e. obj.update(unset__field=1) followed by obj.reload() |
| 803 | delattr(self, field) |
| 804 | |
| 805 | self._changed_fields = ( |
| 806 | list(set(self._changed_fields) - set(fields)) |
| 807 | if fields |
| 808 | else obj._changed_fields |
| 809 | ) |
| 810 | self._created = False |
| 811 | return self |
| 812 | |
| 813 | def _reload(self, key, value): |
| 814 | """Used by :meth:`~mongoengine.Document.reload` to ensure the |