Skip to content

Commit a47bbc4

Browse files
committed
Add the ability to injest a field through multiple names
1 parent a30990f commit a47bbc4

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

pydanticrud/backends/dynamodb.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,13 +117,15 @@ def __init__(self, schema):
117117
self.definitions = schema.get("definitions")
118118

119119
def _get_type_possibilities(self, field_name) -> Set[tuple]:
120-
field_properties = self.properties[field_name]
120+
field_properties = self.properties.get(field_name)
121121

122122
possible_types = []
123123
if "anyOf" in field_properties:
124124
possible_types.extend([r.get("$ref", r) for r in field_properties["anyOf"]])
125-
else:
125+
elif isinstance(field_properties, dict):
126126
possible_types.append(field_properties.get("$ref", field_properties))
127+
else:
128+
return set()
127129

128130
def type_from_definition(definition_signature: Union[str, dict]) -> dict:
129131
if isinstance(definition_signature, str):
@@ -154,6 +156,8 @@ def _serialize_field(self, field_name, value):
154156
except (ValueError, TypeError, KeyError):
155157
pass
156158

159+
# If we got a value that is not part of the schema, pass it
160+
# through and let pydantic sort it out.
157161
return value
158162

159163
def serialize_record(self, data_dict) -> dict:

tests/test_dynamodb.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import random
66

77
import docker
8-
from pydantic import BaseModel as PydanticBaseModel, Field
8+
from pydantic import BaseModel as PydanticBaseModel, Field, root_validator, ValidationError
99
from pydanticrud import BaseModel, DynamoDbBackend, ConditionCheckFailed
1010
import pytest
1111
from pydanticrud.exceptions import DoesNotExist
@@ -46,6 +46,12 @@ class AliasKeyModel(BaseModel):
4646
name: str
4747
type_: str = Field(alias="type")
4848

49+
@root_validator(pre=True)
50+
def type_from_typ(cls, values):
51+
if 'typ' in values:
52+
values['type'] = values.pop('typ')
53+
return values
54+
4955
class Config:
5056
title = "AliasTitle123"
5157
hash_key = "name"
@@ -504,3 +510,13 @@ def test_get_alias_model_data(dynamo, alias_query_data):
504510
data = alias_model_data_generator()
505511
res = AliasKeyModel.get(alias_query_data[0]['name'])
506512
assert res.dict(by_alias=True) == alias_query_data[0]
513+
514+
515+
def test_alias_model_validator_ingest(dynamo):
516+
data = alias_model_data_generator()
517+
AliasKeyModel(**data)
518+
data["typ"] = data.pop("type")
519+
AliasKeyModel(**data)
520+
data.pop("typ")
521+
with pytest.raises(ValidationError):
522+
AliasKeyModel(**data)

0 commit comments

Comments
 (0)