1
1
import typing as t
2
2
from datetime import date , datetime , time
3
+ from enum import Enum
3
4
from uuid import UUID
4
5
5
6
from click import Context , Parameter , ParamType
10
11
from django_typer .completers .model import ModelObjectCompleter
11
12
12
13
14
+ class ReturnType (Enum ):
15
+ MODEL_INSTANCE = 0
16
+ FIELD_VALUE = 1
17
+ QUERY_SET = 2
18
+
19
+
13
20
class ModelObjectParser (ParamType ):
14
21
"""
15
22
A parser that will turn strings into model object instances based on the
@@ -44,6 +51,9 @@ def handle(
44
51
The callable should accept three arguments: the model class, the
45
52
value that failed to lookup, and the exception that was raised.
46
53
If not provided, a CommandError will be raised.
54
+ :param return_type: The model object parser can return types other than the model
55
+ instance (default) - use the ReturnType enumeration to return other types
56
+ from the parser including QuerySets or the primitive values of the model fields.
47
57
"""
48
58
49
59
error_handler = t .Callable [[t .Type [models .Model ], str , Exception ], None ]
@@ -52,6 +62,7 @@ def handle(
52
62
lookup_field : str
53
63
case_insensitive : bool = False
54
64
on_error : t .Optional [error_handler ] = None
65
+ return_type : ReturnType = ReturnType .MODEL_INSTANCE
55
66
56
67
_lookup : str = ""
57
68
_field : models .Field
@@ -90,6 +101,7 @@ def __init__(
90
101
lookup_field : t .Optional [str ] = None ,
91
102
case_insensitive : bool = case_insensitive ,
92
103
on_error : t .Optional [error_handler ] = on_error ,
104
+ return_type : ReturnType = return_type ,
93
105
):
94
106
from django .contrib .contenttypes .fields import GenericForeignKey
95
107
@@ -98,6 +110,7 @@ def __init__(
98
110
lookup_field or getattr (self .model_cls ._meta .pk , "name" , "id" )
99
111
)
100
112
self .on_error = on_error
113
+ self .return_type = return_type
101
114
self .case_insensitive = case_insensitive
102
115
field = self .model_cls ._meta .get_field (self .lookup_field )
103
116
assert not isinstance (field , (models .ForeignObjectRel , GenericForeignKey )), _ (
@@ -126,7 +139,7 @@ def convert(
126
139
"""
127
140
original = value
128
141
try :
129
- if isinstance (value , self . model_cls ):
142
+ if not isinstance (value , str ):
130
143
return value
131
144
elif isinstance (self ._field , models .UUIDField ):
132
145
uuid = ""
@@ -147,6 +160,12 @@ def convert(
147
160
if ambiguous :
148
161
raise ValueError (f"Invalid duration: { value } " )
149
162
value = parsed
163
+ if self .return_type is ReturnType .QUERY_SET :
164
+ return self .model_cls .objects .filter (
165
+ ** {f"{ self .lookup_field } { self ._lookup } " : value }
166
+ )
167
+ elif self .return_type is ReturnType .FIELD_VALUE :
168
+ return value
150
169
return self .model_cls .objects .get (
151
170
** {f"{ self .lookup_field } { self ._lookup } " : value }
152
171
)
0 commit comments