add safe fails for adding and removing not saved models to many to many rel, add tests for save_related

This commit is contained in:
collerek
2020-11-14 14:47:33 +01:00
parent cd33f6a96b
commit 0f36944fe1
4 changed files with 41 additions and 6 deletions

View File

@ -192,7 +192,7 @@ class Model(NewBaseModel):
self.set_save_status(True)
return self
async def save_related(self) -> int:
async def save_related(self) -> int: # noqa: CCR001
update_count = 0
for related in self.extract_related_names():
if self.Meta.model_fields[related].virtual or issubclass(

View File

@ -12,7 +12,7 @@ from typing import (
Union,
)
from ormar.exceptions import RelationshipInstanceError
from ormar.exceptions import ModelPersistenceError, RelationshipInstanceError
try:
import orjson as json
@ -63,8 +63,14 @@ class ModelTableProxy:
target_field = cls.Meta.model_fields[field]
target_pkname = target_field.to.Meta.pkname
if isinstance(field_value, ormar.Model):
model_dict[field] = getattr(field_value, target_pkname)
elif field_value:
pk_value = getattr(field_value, target_pkname)
if not pk_value:
raise ModelPersistenceError(
f"You cannot save {field_value.get_name()} "
f"model without pk set!"
)
model_dict[field] = pk_value
elif field_value: # nested dict
model_dict[field] = field_value.get(target_pkname)
else:
model_dict.pop(field, None)