Skip to content

Commit

Permalink
many-to-many nullable columns with through
Browse files Browse the repository at this point in the history
  • Loading branch information
nikelborm authored and collerek committed Dec 10, 2022
1 parent 7c18fa5 commit 4b7de5a
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
4 changes: 4 additions & 0 deletions ormar/fields/many_to_many.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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), {})
Expand Down
7 changes: 4 additions & 3 deletions ormar/models/helpers/sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 4b7de5a

Please sign in to comment.