Fix: move documents when a tag is cleared through the reverse relation

This commit is contained in:
Trenton H committed 2026-11-15 15:07:59 -08:00
1 parent b2160ca860
commit 18f243d381
2 files changed
+70 -1

No files matched your search

+14 -1
View File
@@ -424,6 +424,16 @@ def update_filename_and_move_files(
**kwargs,
) -> None:
action = kwargs.get("action")
if kwargs.get("reverse") and action == "pre_clear":
# tag.documents.clear(): Django sends pk_set=None for both clear
# actions, and the rows are gone by post_clear. Remember the affected
# documents here, on the instance both signals share.
instance._cleared_document_pks = list(
instance.documents.values_list("pk", flat=True),
)
return
if action is not None and action not in {"post_add", "post_remove", "post_clear"}:
# m2m_changed fires pre_* and post_* actions; only post_* describe the
# relation state the filename should follow.
@@ -431,7 +441,10 @@ def update_filename_and_move_files(
if kwargs.get("reverse"):
# tag.documents.add(doc): instance is the Tag, pk_set holds Document pks.
for document in Document.objects.filter(pk__in=kwargs.get("pk_set") or ()):
pk_set = kwargs.get("pk_set")
if action == "post_clear":
pk_set = instance.__dict__.pop("_cleared_document_pks", ())
for document in Document.objects.filter(pk__in=pk_set or ()):
request_file_move(document)
return
+56
View File
@@ -689,6 +689,62 @@ class TestReceiver:
request.assert_called_once()
assert request.call_args.args[0].pk == document.pk
def test_reverse_clear_requests_a_move_per_cleared_document(
self,
mocker: MockerFixture,
) -> None:
"""
GIVEN:
- A tag on two documents, and one document without it
WHEN:
- The tag's reverse relation is cleared
THEN:
- A move is requested for each cleared document, and no other
"""
tag = TagFactory()
first = DocumentFactory.create()
second = DocumentFactory.create()
other = DocumentFactory.create()
first.tags.add(tag)
second.tags.add(tag)
request = mocker.patch("documents.signals.handlers.request_file_move")
tag.documents.clear()
assert {call.args[0].pk for call in request.call_args_list} == {
first.pk,
second.pk,
}
assert other.pk not in {call.args[0].pk for call in request.call_args_list}
def test_reverse_clear_moves_file_for_tag_in_template(
self,
document: Document,
paperless_dirs: PaperlessDirs,
settings: Settings,
) -> None:
"""
GIVEN:
- A document whose filename depends on its tag
WHEN:
- The tag is removed through the reverse relation's clear()
THEN:
- The file and filename follow the document's new state
"""
settings.FILENAME_FORMAT = "{tag_list}/{title}"
tag = TagFactory(name="clearme")
with defer_file_moves():
document.tags.add(tag)
document.refresh_from_db()
assert document.filename == "clearme/original.pdf"
with defer_file_moves():
tag.documents.clear()
document.refresh_from_db()
assert document.filename == "original.pdf"
assert (paperless_dirs.originals_dir / "original.pdf").is_file()
@pytest.mark.django_db
class TestDeferFileMoves: