1
0
mirror of https://github.com/openSUSE/osc.git synced 2025-01-23 13:31:48 +01:00

Drop unused 'exclude_unset' argument from BaseModel.dict() method

This commit is contained in:
Daniel Mach 2024-01-04 08:39:06 +01:00
parent 16cdc067a5
commit b8d6c949c9
2 changed files with 11 additions and 9 deletions

View File

@ -324,16 +324,13 @@ class BaseModel(metaclass=ModelMeta):
self._allow_new_attributes = False self._allow_new_attributes = False
def dict(self, exclude_unset=False): def dict(self):
result = {} result = {}
for name, field in self.__fields__.items(): for name, field in self.__fields__.items():
if field.exclude: if field.exclude:
continue continue
if exclude_unset and field.name not in self._values and field.is_optional:
# include only mandatory fields and optional fields that were set to an actual value
continue
if field.is_model: if field.is_model:
result[name] = getattr(self, name).dict(exclude_unset=exclude_unset) result[name] = getattr(self, name).dict()
else: else:
result[name] = getattr(self, name) result[name] = getattr(self, name)
return result return result

View File

@ -24,16 +24,21 @@ class TestNotSet(unittest.TestCase):
class Test(unittest.TestCase): class Test(unittest.TestCase):
def test_modified(self): def test_dict(self):
class TestSubmodel(BaseModel):
text: str = Field(default="default")
class TestModel(BaseModel): class TestModel(BaseModel):
a: str = Field(default="default") a: str = Field(default="default")
b: Optional[str] = Field(default=None) b: Optional[str] = Field(default=None)
sub: Optional[List[TestSubmodel]] = Field(default=None)
m = TestModel() m = TestModel()
self.assertEqual(m.dict(exclude_unset=True), {"a": "default"}) self.assertEqual(m.dict(), {"a": "default", "b": None, "sub": None})
m = TestModel(b=None) m.b = "B"
self.assertEqual(m.dict(exclude_unset=True), {"a": "default", "b": None}) m.sub = [{"text": "one"}, {"text": "two"}]
self.assertEqual(m.dict(), {"a": "default", "b": "B", "sub": [{"text": "one"}, {"text": "two"}]})
def test_unknown_fields(self): def test_unknown_fields(self):
class TestModel(BaseModel): class TestModel(BaseModel):