Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/releases.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@
fields, if any), and `remove()` emptying the in-memory relation before the
through rows were deleted. `remove()` now deletes all matching through rows.
[#1821](https://github.com/ormar-orm/ormar/issues/1821)
* Raise `QueryDefinitionError` when `update()` or `delete()` is called on a
queryset filtered or excluded by a related model's field (e.g.
`filter(category__name="x")`), instead of generating an invalid statement
that ignores or fails on the missing join
— thanks @moneebullah25 [#1817](https://github.com/ormar-orm/ormar/issues/1817)

## 0.26.0

Expand Down
20 changes: 20 additions & 0 deletions ormar/queryset/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -871,6 +871,24 @@ async def avg(self, columns: Union[str, list[str]]) -> Any:
columns = [columns]
return await self._query_aggr_function(func_name="avg", columns=columns)

def _verify_no_related_filters(self, operation: str) -> None:
"""
Raises if any filter or exclude clause targets a related model, as
UPDATE and DELETE statements do not join the related tables.

:param operation: name of the operation, used in the error message
:type operation: str
"""
for clause in self.filter_clauses + self.exclude_clauses:
actions = clause._iter() if isinstance(clause, FilterGroup) else [clause]
for action in actions:
if action.related_parts:
raise QueryDefinitionError(
f"{operation}() does not support filters on related models "
f"('{action.query_str}'). Select the pks first and "
f"filter with pk__in instead."
)

async def update(self, each: bool = False, **kwargs: Any) -> int:
"""
Updates the model table after applying the filters from kwargs.
Expand All @@ -891,6 +909,7 @@ async def update(self, each: bool = False, **kwargs: Any) -> int:
"If you want to update all rows use update(each=True, **kwargs)"
)

self._verify_no_related_filters("update")
self_fields = self.model.extract_db_own_fields().union(
self.model.extract_related_names()
)
Expand Down Expand Up @@ -929,6 +948,7 @@ async def delete(self, *args: Any, each: bool = False, **kwargs: Any) -> int:
"You cannot delete without filtering the queryset first. "
"If you want to delete all rows use delete(each=True)"
)
self._verify_no_related_filters("delete")
expr = FilterQuery(filter_clauses=self.filter_clauses).apply(
self.table.delete() # type: ignore
)
Expand Down
35 changes: 35 additions & 0 deletions tests/test_queries/test_queryset_level_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,41 @@ async def test_get_or_create_with_defaults():
assert book2 == book


@pytest.mark.asyncio
async def test_update_and_delete_with_related_filter_raise():
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
category = await Category.objects.create(name="x")
await Note.objects.create(text="a", category=category)
await Note.objects.create(text="b")

with pytest.raises(QueryDefinitionError):
await Note.objects.filter(category__name="x").update(text="z")
with pytest.raises(QueryDefinitionError):
await Note.objects.exclude(category__name="x").update(text="z")
with pytest.raises(QueryDefinitionError):
await Note.objects.filter(
ormar.or_(category__name="x", text="b")
).delete()
with pytest.raises(QueryDefinitionError):
await Note.objects.delete(category__name="x")

with pytest.raises(QueryDefinitionError):
await Note.objects.filter(
ormar.and_(ormar.or_(category__name__icontains="x"))
).delete()
with pytest.raises(QueryDefinitionError):
await Note.objects.exclude(category__name="x").delete()

assert await Note.objects.filter(text="z").count() == 0
assert await Note.objects.count() == 2

assert await Note.objects.filter(category=category).update(text="z") == 1
assert await Note.objects.filter(text="z").count() == 1
assert await Note.objects.filter(category=category).delete() == 1
assert await Note.objects.count() == 1


@pytest.mark.asyncio
async def test_update_or_create():
async with base_ormar_config.database:
Expand Down
Loading