From bac4059efd9d52a098ea731d8f7d45a2a559fb84 Mon Sep 17 00:00:00 2001 From: Radoslav Georgiev Date: Tue, 29 Nov 2022 14:54:40 +0200 Subject: [PATCH] Bump `Handling updates with a service` section - Remove the early copy-pasted version of `model_update` - Stick to linking to the actual current implementation of `model_update` --- README.md | 29 +++-------------------------- 1 file changed, 3 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index d356d93..d5c0ff6 100644 --- a/README.md +++ b/README.md @@ -2716,38 +2716,15 @@ def user_update(*, user: User, data) -> User: - We're calling the generic `model_update` service for the fields that have no side-effects related to them (meaning that they're just set to the value that we provide). - This pattern allows us to extract the repetitive field setting in a generic service and perform only the specific tasks inside of the update service (side-effects). - -The generic `model_update` implementation looks like this: - -```python -def model_update( - *, - instance: DjangoModelType, - fields: List[str], - data: Dict[str, Any] -) -> Tuple[DjangoModelType, bool]: - has_updated = False - - for field in fields: - if field not in data: - continue - - if getattr(instance, field) != data[field]: - has_updated = True - setattr(instance, field, data[field]) - - if has_updated: - instance.full_clean() - instance.save(update_fields=fields) - - return instance, has_updated -``` +- We can be smart & provide the `update_fields` kwarg, when saving the instance. This way, in the `UPDATE` query, we'll only send values that are actually updated. The full implementations of these services can be found in our example project: - [`model_update`](https://github.com/HackSoftware/Django-Styleguide-Example/blob/master/styleguide_example/common/services.py) - [`user_update`](https://github.com/HackSoftware/Django-Styleguide-Example/blob/master/styleguide_example/users/services.py) +If you are going to include `model_update` in your project, make sure to [read the tests](https://github.com/HackSoftware/Django-Styleguide-Example/blob/master/styleguide_example/common/tests/services/test_model_update.py) & include them too! + ## DX (Developer Experience) A section with various things that can make your Django developer life better.