mirror of
https://github.com/openSUSE/osc.git
synced 2025-01-01 04:36:13 +01:00
Fix BaseModel to convert dictionaries to objects on retrieving a model list
This commit is contained in:
parent
acc54919fc
commit
7768684461
@ -249,8 +249,18 @@ class Field(property):
|
|||||||
def get(self, obj):
|
def get(self, obj):
|
||||||
try:
|
try:
|
||||||
result = obj._values[self.name]
|
result = obj._values[self.name]
|
||||||
|
|
||||||
|
# convert dictionaries into objects
|
||||||
|
# we can't do it earlier because list is a standalone object that is not under our control
|
||||||
|
if result is not None and self.is_model_list:
|
||||||
|
for num, i in enumerate(result):
|
||||||
|
if isinstance(i, dict):
|
||||||
|
klass = self.inner_type
|
||||||
|
result[num] = klass(**i)
|
||||||
|
|
||||||
if self.get_callback is not None:
|
if self.get_callback is not None:
|
||||||
result = self.get_callback(obj, result)
|
result = self.get_callback(obj, result)
|
||||||
|
|
||||||
return result
|
return result
|
||||||
except KeyError:
|
except KeyError:
|
||||||
pass
|
pass
|
||||||
|
@ -339,6 +339,19 @@ class Test(unittest.TestCase):
|
|||||||
m.field = [{"text": "one"}, {"text": "two"}]
|
m.field = [{"text": "one"}, {"text": "two"}]
|
||||||
self.assertFalse(m.has_changed())
|
self.assertFalse(m.has_changed())
|
||||||
|
|
||||||
|
def test_append_dict(self):
|
||||||
|
class TestSubmodel(BaseModel):
|
||||||
|
text: str = Field(default="default")
|
||||||
|
|
||||||
|
class TestModel(BaseModel):
|
||||||
|
field: Optional[List[TestSubmodel]] = Field(default=[])
|
||||||
|
|
||||||
|
m = TestModel()
|
||||||
|
m.field.append({"text": "value"})
|
||||||
|
# dict is converted to object next time the field is retrieved
|
||||||
|
self.assertIsInstance(m.field[0], BaseModel)
|
||||||
|
self.assertEqual(m.field[0].text, "value")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
Loading…
Reference in New Issue
Block a user