11import inspect
2+ import uuid
23from typing import Type , Union
34
45from django .apps import apps
1920"""
2021
2122
23+ class StandInPK :
24+ def __init__ (self , ct : models .Model ):
25+ self .pk_field_type = ct .pk_field_type
26+
27+ def get_prep_value (self , value : Union [str , int , uuid .UUID ]) -> Union [str , int ]:
28+ if self .pk_field_type == "uuid" :
29+ if isinstance (value , uuid .UUID ):
30+ return str (value )
31+ return str (uuid .UUID (value ))
32+ return int (value )
33+
34+ def to_python (self , value : Union [str , int , uuid .UUID ]) -> Union [int , uuid .UUID ]:
35+ if self .pk_field_type == "uuid" :
36+ if isinstance (value , uuid .UUID ):
37+ return value
38+ return uuid .UUID (value )
39+ return int (value )
40+
41+
2242class StandinMeta :
2343 def __init__ (self , ct : models .Model , abstract = False ):
2444 self .service = ct .service
2545 self .model_name = ct .model
2646 self .app_label = ct .app_label
2747 self .abstract = abstract
2848
29- class PK :
30- def __init__ (self , pk_field_type ):
31- self .pk_field_type = pk_field_type
32-
33- def get_prep_value (self , value ):
34- # TODO: handle uuid fields based on
35- # if self.pk_field_type:
36- return int (value )
37-
38- def to_python (self , value ):
39- return int (value )
40-
41- self .pk = PK (ct .pk_field_type )
49+ self .pk = StandInPK (ct )
4250
4351
4452class RemoteObject :
@@ -54,6 +62,12 @@ def __init__(self, content_type: models.Model, object_id: Union[int, str]):
5462 if content_type .model != self ._meta .model_name :
5563 raise RuntimeError (f'RemoteObject created with type { content_type } but with type for { self ._meta .model_name } ' )
5664
65+ # Raise an early error if the primary key is obviously not valid for the model type
66+ try :
67+ self ._meta .pk .to_python (object_id )
68+ except (ValueError , TypeError , AttributeError ) as e :
69+ raise ValueError (f"Invalid primary key value { object_id } for type { content_type .pk_field_type } , error: { e } " )
70+
5771 def __repr__ (self ):
5872 return f"<RemoteObject { self .content_type } id={ self .object_id } >"
5973
0 commit comments