diff options
| author | Adam Johnson <me@adamj.eu> | 2021-12-13 15:44:07 +0000 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2022-01-13 11:09:37 +0100 |
| commit | 08d8bccbf1b0764a0de68325569ee47da256e206 (patch) | |
| tree | f5efe9496dedba0f7744ba87c5ef807b1b7d1fe8 /django | |
| parent | 0a4a5e5bacc354df3132d0fcf706839c21afb89d (diff) | |
Improved Model.__init__() properties loop.
This improves readability, accumulates unrecognized arguments raise an
exception with all of them, and avoids refetching the values.
Diffstat (limited to 'django')
| -rw-r--r-- | django/db/models/base.py | 33 |
1 files changed, 21 insertions, 12 deletions
diff --git a/django/db/models/base.py b/django/db/models/base.py index 793cd936f1..37f6a3dd58 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -513,18 +513,27 @@ class Model(metaclass=ModelBase): if kwargs: property_names = opts._property_names - for prop in tuple(kwargs): - try: - # Any remaining kwargs must correspond to properties or - # virtual fields. - if prop in property_names or opts.get_field(prop): - if kwargs[prop] is not _DEFERRED: - _setattr(self, prop, kwargs[prop]) - del kwargs[prop] - except (AttributeError, FieldDoesNotExist): - pass - for kwarg in kwargs: - raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) + unexpected = () + for prop, value in kwargs.items(): + # Any remaining kwargs must correspond to properties or virtual + # fields. + if prop in property_names: + if value is not _DEFERRED: + _setattr(self, prop, value) + else: + try: + opts.get_field(prop) + except FieldDoesNotExist: + unexpected += (prop,) + else: + if value is not _DEFERRED: + _setattr(self, prop, value) + if unexpected: + unexpected_names = ', '.join(repr(n) for n in unexpected) + raise TypeError( + f'{cls.__name__}() got unexpected keyword arguments: ' + f'{unexpected_names}' + ) super().__init__() post_init.send(sender=cls, instance=self) |
