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

1""" 

2---------------------------------------------------------------------------- 

3 

4 METADATA: 

5 

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 

13 

14---------------------------------------------------------------------------- 

15 

16 LAST MODIFIED: 

17 

18 2025-03-04 By Jess Mann 

19 

20""" 

21 

22from __future__ import annotations 

23 

24from datetime import datetime 

25from typing import TYPE_CHECKING, Any 

26 

27from pydantic import Field, field_validator 

28 

29from paperap.const import CustomFieldTypes 

30from paperap.models.abstract.model import StandardModel 

31 

32if TYPE_CHECKING: 

33 from paperap.models.document import DocumentQuerySet 

34 

35 

36class CustomField(StandardModel): 

37 """ 

38 Represents a custom field in Paperless-NgX. 

39 """ 

40 

41 name: str 

42 data_type: CustomFieldTypes | None = None 

43 

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. 

49 

50 Args: 

51 v: The value to validate. 

52 

53 Returns: 

54 The validated value. 

55 

56 Raises: 

57 ValueError: If the value is not a valid data type. 

58 

59 """ 

60 if v is None: 

61 return v 

62 

63 if isinstance(v, CustomFieldTypes): 

64 return v 

65 

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__)}") 

72 

73 return v 

74 

75 extra_data: dict[str, Any] = Field(default_factory=dict) 

76 document_count: int = 0 

77 

78 model_config = { 

79 "arbitrary_types_allowed": True, 

80 "populate_by_name": True, 

81 "extra": "allow", 

82 } 

83 

84 class Meta(StandardModel.Meta): 

85 # Fields that should not be modified 

86 read_only_fields = {"slug"} 

87 

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)