From 4b7de5abce78a0266e157fc2a9039042c5a35cc9 Mon Sep 17 00:00:00 2001 From: nikelborm Date: Tue, 27 Sep 2022 03:03:21 +0300 Subject: [PATCH] many-to-many nullable columns with through --- ormar/fields/many_to_many.py | 4 ++++ ormar/models/helpers/sqlalchemy.py | 7 ++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/ormar/fields/many_to_many.py b/ormar/fields/many_to_many.py index 350fa3c38..bc212fcb6 100644 --- a/ormar/fields/many_to_many.py +++ b/ormar/fields/many_to_many.py @@ -124,6 +124,8 @@ def ManyToMany( # type: ignore through_relation_name = kwargs.pop("through_relation_name", None) through_reverse_relation_name = kwargs.pop("through_reverse_relation_name", None) + is_through_relation_column_nullable = kwargs.pop("is_through_relation_column_nullable", None) + is_through_reverse_relation_column_nullable = kwargs.pop("is_through_reverse_relation_column_nullable", None) if through is not None and through.__class__ != ForwardRef: forbid_through_relations(cast(Type["Model"], through)) @@ -167,6 +169,8 @@ def ManyToMany( # type: ignore skip_field=skip_field, through_relation_name=through_relation_name, through_reverse_relation_name=through_reverse_relation_name, + is_through_reverse_relation_column_nullable=is_through_reverse_relation_column_nullable, + is_through_relation_column_nullable=is_through_relation_column_nullable, ) Field = type("ManyToMany", (ManyToManyField, BaseField), {}) diff --git a/ormar/models/helpers/sqlalchemy.py b/ormar/models/helpers/sqlalchemy.py index b0ade1d02..d0e430b2d 100644 --- a/ormar/models/helpers/sqlalchemy.py +++ b/ormar/models/helpers/sqlalchemy.py @@ -44,10 +44,10 @@ def adjust_through_many_to_many_model(model_field: "ManyToManyField") -> None: ) create_and_append_m2m_fk( - model=model_field.to, model_field=model_field, field_name=parent_name + model=model_field.to, model_field=model_field, field_name=parent_name, nullable=model_field.is_through_reverse_relation_column_nullable, ) create_and_append_m2m_fk( - model=model_field.owner, model_field=model_field, field_name=child_name + model=model_field.owner, model_field=model_field, field_name=child_name, nullable=model_field.is_through_relation_column_nullable, ) create_pydantic_field(parent_name, model_field.to, model_field) @@ -58,7 +58,7 @@ def adjust_through_many_to_many_model(model_field: "ManyToManyField") -> None: def create_and_append_m2m_fk( - model: Type["Model"], model_field: "ManyToManyField", field_name: str + model: Type["Model"], model_field: "ManyToManyField", field_name: str, nullable: bool ) -> None: """ Registers sqlalchemy Column with sqlalchemy.ForeignKey leading to the model. @@ -88,6 +88,7 @@ def create_and_append_m2m_fk( name=f"fk_{model_field.through.Meta.tablename}_{model.Meta.tablename}" f"_{field_name}_{pk_alias}", ), + nullable=nullable, ) model_field.through.Meta.columns.append(column) model_field.through.Meta.table.append_column(column)