Coverage for src/paperap/models/custom_field/model.py: 83%
30 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-22 16:02 -0400
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-22 16:02 -0400
1"""
2----------------------------------------------------------------------------
4 METADATA:
6 File: custom_field.py
7 Project: paperap
8 Created: 2025-03-04
9 Version: 0.0.9
10 Author: Jess Mann
11 Email: jess@jmann.me
12 Copyright (c) 2025 Jess Mann
14----------------------------------------------------------------------------
16 LAST MODIFIED:
18 2025-03-04 By Jess Mann
20"""
22from __future__ import annotations
24from datetime import datetime
25from typing import TYPE_CHECKING, Any
27from pydantic import Field, field_validator
29from paperap.const import CustomFieldTypes
30from paperap.models.abstract.model import StandardModel
32if TYPE_CHECKING:
33 from paperap.models.document import DocumentQuerySet
36class CustomField(StandardModel):
37 """
38 Represents a custom field in Paperless-NgX.
39 """
41 name: str
42 data_type: CustomFieldTypes | None = None
44 @field_validator("data_type", mode="before")
45 @classmethod
46 def validate_data_type(cls, v: Any) -> CustomFieldTypes | None:
47 """
48 Validate the data_type field.
50 Args:
51 v: The value to validate.
53 Returns:
54 The validated value.
56 Raises:
57 ValueError: If the value is not a valid data type.
59 """
60 if v is None:
61 return v
63 if isinstance(v, CustomFieldTypes):
64 return v
66 if isinstance(v, str):
67 try:
68 # Try to convert string to enum
69 return CustomFieldTypes(v)
70 except (ValueError, TypeError):
71 raise ValueError(f"data_type must be a valid CustomFieldTypes: {', '.join(CustomFieldTypes.__members__)}")
73 return v
75 extra_data: dict[str, Any] = Field(default_factory=dict)
76 document_count: int = 0
78 model_config = {
79 "arbitrary_types_allowed": True,
80 "populate_by_name": True,
81 "extra": "allow",
82 }
84 class Meta(StandardModel.Meta):
85 # Fields that should not be modified
86 read_only_fields = {"slug"}
88 @property
89 def documents(self) -> "DocumentQuerySet":
90 """
91 Get documents with this custom field.
92 """
93 return self._client.documents().all().has_custom_field_id(self.id)