From 2cc3b55a7c73a3b7aaedbd4b451ee32335c31820 Mon Sep 17 00:00:00 2001 From: collerek Date: Fri, 2 Apr 2021 11:27:22 +0200 Subject: [PATCH] fix bulk_create trying to save property fields and pydantic fields --- docs/releases.md | 1 + ormar/models/mixins/save_mixin.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/docs/releases.md b/docs/releases.md index e52d34f..ce9daa7 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -25,6 +25,7 @@ * Fix hitting recursion error with very complicated models structure with loops when calling `dict()`. * Fix bug when two non-relation fields were merged (appended) in query result when they were not relation fields (i.e. JSON) * Fix bug when during translation to dict from list the same relation name is used in chain but leads to different models +* Fix bug when bulk_create would try to save also `property_field` decorated methods and `pydantic` fields ## Other diff --git a/ormar/models/mixins/save_mixin.py b/ormar/models/mixins/save_mixin.py index dfca964..5ade49f 100644 --- a/ormar/models/mixins/save_mixin.py +++ b/ormar/models/mixins/save_mixin.py @@ -32,11 +32,29 @@ class SavePrepareMixin(RelationMixin, AliasMixin): :rtype: Dict[str, str] """ new_kwargs = cls._remove_pk_from_kwargs(new_kwargs) + new_kwargs = cls._remove_not_ormar_fields(new_kwargs) new_kwargs = cls.substitute_models_with_pks(new_kwargs) new_kwargs = cls.populate_default_values(new_kwargs) new_kwargs = cls.translate_columns_to_aliases(new_kwargs) return new_kwargs + @classmethod + def _remove_not_ormar_fields(cls, new_kwargs: dict) -> dict: + """ + Removes primary key for if it's nullable or autoincrement pk field, + and it's set to None. + + :param new_kwargs: dictionary of model that is about to be saved + :type new_kwargs: Dict[str, str] + :return: dictionary of model that is about to be saved + :rtype: Dict[str, str] + """ + ormar_fields = { + k for k, v in cls.Meta.model_fields.items() if not v.pydantic_only + } + new_kwargs = {k: v for k, v in new_kwargs.items() if k in ormar_fields} + return new_kwargs + @classmethod def _remove_pk_from_kwargs(cls, new_kwargs: dict) -> dict: """