| 1 |
from typing import TYPE_CHECKING |
| 2 |
|
| 3 |
from beanie.odm.utils.encoder import Encoder |
| 4 |
|
| 5 |
if TYPE_CHECKING: |
| 6 |
from beanie.odm.documents import Document |
| 7 |
|
| 8 |
|
| 9 |
def get_dict( |
| 10 |
document: "Document", |
| 11 |
to_db: bool = False, |
| 12 |
exclude: set[str] | None = None, |
| 13 |
keep_nulls: bool = True, |
| 14 |
): |
| 15 |
if exclude is None: |
| 16 |
exclude = set() |
| 17 |
if document.id is None: |
| 18 |
exclude.add("_id") |
| 19 |
include = set() |
| 20 |
if document.get_settings().use_revision: |
| 21 |
include.add("revision_id") |
| 22 |
# Explicit excludes take precedence over includes |
| 23 |
include -= exclude |
| 24 |
encoder = Encoder( |
| 25 |
exclude=exclude, include=include, to_db=to_db, keep_nulls=keep_nulls |
| 26 |
) |
| 27 |
return encoder.encode(document) |
| 28 |
|
| 29 |
|
| 30 |
def get_nulls( |
| 31 |
document: "Document", |
| 32 |
exclude: set[str] | None = None, |
| 33 |
): |
| 34 |
dictionary = get_dict(document, exclude=exclude, keep_nulls=True) |
| 35 |
return filter_none(dictionary) |
| 36 |
|
| 37 |
|
| 38 |
def get_top_level_nones( |
| 39 |
document: "Document", |
| 40 |
exclude: set[str] | None = None, |
| 41 |
): |
| 42 |
if exclude is None: |
| 43 |
exclude = set() |
| 44 |
# revision_id is managed separately by SetRevisionId in the update |
| 45 |
# pipeline - including it here would conflict with the $set that |
| 46 |
# SetRevisionId produces, causing a MongoDB OperationFailure. |
| 47 |
if document.get_settings().use_revision: |
| 48 |
exclude.add("revision_id") |
| 49 |
dictionary = get_dict(document, exclude=exclude, keep_nulls=True) |
| 50 |
return {k: v for k, v in dictionary.items() if v is None} |
| 51 |
|
| 52 |
|
| 53 |
def filter_none(d): |
| 54 |
result = {} |
| 55 |
for k, v in d.items(): |
| 56 |
if isinstance(v, dict): |
| 57 |
filtered = filter_none(v) |
| 58 |
if filtered: |
| 59 |
result[k] = filtered |
| 60 |
elif v is None: |
| 61 |
result[k] = v |
| 62 |
return result |