Repository: paperless-ngx/paperless-ngx

Issue:
[BUG] Unable to save doc link when target doc has value None
### Description

If I want to save a document that contains a custom field with an unfilled document link, an error 500 occurs and a trace is thrown in the server log.

### Steps to reproduce

- add a custom field with a document link
- add a document
- save the document

### Webserver logs

```bash
[2023-12-31 07:39:46,111] [ERROR] [django.request] Internal Server Error: /api/documents/38/
Traceback (most recent call last):
  File "/usr/local/lib/python3.11/site-packages/asgiref/sync.py", line 534, in thread_handler
    raise exc_info[1]
  File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = await get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/asgiref/sync.py", line 534, in thread_handler
    raise exc_info[1]
  File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 253, in _get_response_async
    response = await wrapped_callback(
               ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/asgiref/sync.py", line 479, in __call__
    ret: _R = await loop.run_in_executor(
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/asgiref/current_thread_executor.py", line 40, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/asgiref/sync.py", line 538, in thread_handler
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view
    return view_func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/paperless/src/documents/views.py", line 319, in update
    response = super().update(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/rest_framework/mixins.py", line 68, in update
    self.perform_update(serializer)
  File "/usr/local/lib/python3.11/site-packages/rest_framework/mixins.py", line 78, in perform_update
    serializer.save()
  File "/usr/local/lib/python3.11/site-packages/drf_writable_nested/mixins.py", line 233, in save
    return super(BaseNestedModelSerializer, self).save(**kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/rest_framework/serializers.py", line 207, in save
    self.instance = self.update(self.instance, validated_data)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/paperless/src/documents/serialisers.py", line 652, in update
    super().update(instance, validated_data)
  File "/usr/src/paperless/src/documents/serialisers.py", line 267, in update
    return super().update(instance, validated_data)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/drf_writable_nested/mixins.py", line 290, in update
    self.update_or_create_reverse_relations(instance, reverse_relations)
  File "/usr/local/lib/python3.11/site-packages/drf_writable_nested/mixins.py", line 188, in update_or_create_reverse_relations
    related_instance = serializer.save(**save_kwargs)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/rest_framework/serializers.py", line 212, in save
    self.instance = self.create(validated_data)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/paperless/src/documents/serialisers.py", line 476, in create
    self.reflect_doclinks(document, custom_field, validated_data["value"])
  File "/usr/src/paperless/src/documents/serialisers.py", line 548, in reflect_doclinks
    elif document.id not in target_doc_field_instance.value:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: argument of type 'NoneType' is not iterable
```


### Browser logs

_No response_

### Paperless-ngx version

2.2.1

### Host OS

Ubuntu 22.04

### Installation method

Docker - official image

### Browser

_No response_

### Configuration changes

_No response_

### Other

_No response_

### Please confirm the following

- [X] I believe this issue is a bug that affects all users of Paperless-ngx, not something specific to my installation.
- [X] I have already searched for relevant existing issues and discussions before opening this report.
- [X] I have updated the title field above with a concise description.


Discussion:

Resolving patch:
diff --git a/src/documents/serialisers.py b/src/documents/serialisers.py
--- a/src/documents/serialisers.py
+++ b/src/documents/serialisers.py
@@ -566,6 +566,9 @@ def reflect_doclinks(
                         value_document_ids=[document.id],
                     ),
                 )
+            elif target_doc_field_instance.value is None:
+                target_doc_field_instance.value_document_ids = [document.id]
+                custom_field_instances_to_update.append(target_doc_field_instance)
             elif document.id not in target_doc_field_instance.value:
                 target_doc_field_instance.value_document_ids.append(document.id)
                 custom_field_instances_to_update.append(target_doc_field_instance)


Test patch:
diff --git a/src/documents/tests/test_api_custom_fields.py b/src/documents/tests/test_api_custom_fields.py
--- a/src/documents/tests/test_api_custom_fields.py
+++ b/src/documents/tests/test_api_custom_fields.py
@@ -530,7 +530,7 @@ def test_custom_field_not_null(self):
 
         self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
 
-    def test_bidirectional_doclink_fields(self):
+    def test_symmetric_doclink_fields(self):
         """
         GIVEN:
             - Existing document
@@ -637,3 +637,28 @@ def test_bidirectional_doclink_fields(self):
         self.assertEqual(doc2.custom_fields.first().value, [])
         self.assertEqual(doc3.custom_fields.first().value, [4])
         self.assertEqual(doc4.custom_fields.first().value, [3])
+
+        # If field exists on target doc but value is None
+        doc5 = Document.objects.create(
+            title="WOW5",
+            content="the content4",
+            checksum="5",
+            mime_type="application/pdf",
+        )
+        CustomFieldInstance.objects.create(document=doc5, field=custom_field_doclink)
+
+        resp = self.client.patch(
+            f"/api/documents/{doc1.id}/",
+            data={
+                "custom_fields": [
+                    {
+                        "field": custom_field_doclink.id,
+                        "value": [doc5.id],
+                    },
+                ],
+            },
+            format="json",
+        )
+
+        self.assertEqual(resp.status_code, status.HTTP_200_OK)
+        self.assertEqual(doc5.custom_fields.first().value, [1])