Skip to content

Commit 613cd8c

Browse files
authored
fix: empty Entities for optional LocalStructuredProperty fields (#370)
* fix: empty Entities for optional LocalStructuredProperty fields Fixes #369
1 parent 5aa8632 commit 613cd8c

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

packages/google-cloud-ndb/google/cloud/ndb/model.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4360,9 +4360,12 @@ def _to_datastore(self, entity, data, prefix="", repeated=False):
43604360
values = [values]
43614361
legacy_values = []
43624362
for value in values:
4363-
legacy_values.append(
4364-
_entity_to_ds_entity(value, set_key=self._keep_keys)
4365-
)
4363+
ds_entity = None
4364+
if value is not None:
4365+
ds_entity = _entity_to_ds_entity(
4366+
value, set_key=self._keep_keys
4367+
)
4368+
legacy_values.append(ds_entity)
43664369
if not self._repeated:
43674370
legacy_values = legacy_values[0]
43684371
data[self._name] = legacy_values

packages/google-cloud-ndb/tests/unit/test_model.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3756,6 +3756,26 @@ class SubKind(model.Model):
37563756
ds_entity = model._entity_to_ds_entity(entity, set_key=False)
37573757
assert prop._call_from_base_type(ds_entity) == entity
37583758

3759+
@staticmethod
3760+
def test_legacy_optional_local_structured_property(in_context):
3761+
class SubKind(model.Model):
3762+
foo = model.Property()
3763+
3764+
class ContainerB(model.Model):
3765+
child_b = model.LocalStructuredProperty(SubKind)
3766+
3767+
class ContainerA(model.Model):
3768+
child_a = model.LocalStructuredProperty(ContainerB)
3769+
3770+
with in_context.new(legacy_data=True).use():
3771+
entity = ContainerA(child_a=ContainerB())
3772+
data = {"_exclude_from_indexes": []}
3773+
assert ContainerA.child_a._to_datastore(entity, data) == (
3774+
"child_a",
3775+
)
3776+
assert data.pop("_exclude_from_indexes") == ["child_a"]
3777+
assert data["child_a"]["child_b"] is None
3778+
37593779

37603780
class TestGenericProperty:
37613781
@staticmethod

0 commit comments

Comments
 (0)