@@ -97,18 +97,26 @@ def register_related(self, key, model, collection):
9797 # Get the foreign key value from the model
9898 foreign_key_value = getattr (model , self .local_key )
9999
100+ # If foreign key is None, register None as the relationship
101+ if foreign_key_value is None :
102+ model .add_relation ({key : None })
103+ return
104+
105+ # Convert foreign key to string for consistent lookup
106+ foreign_key_value = str (foreign_key_value )
107+
100108 # If collection is a dict (mapped), use it directly
101109 if isinstance (collection , dict ):
102110 related = collection .get (foreign_key_value )
103111 else :
104112 # Otherwise find the related model in the collection
105113 related = None
106114 for item in collection :
107- if getattr (item , self .foreign_key ) == foreign_key_value :
115+ if str ( getattr (item , self .foreign_key ) ) == foreign_key_value :
108116 related = item
109117 break
110118
111- # Register the relationship
119+ # Register the relationship with the model instance
112120 model .add_relation ({key : related })
113121
114122 def map_related (self , related_result ):
@@ -122,7 +130,9 @@ def map_related(self, related_result):
122130 """
123131 mapped = {}
124132 for item in related_result :
125- mapped [getattr (item , self .foreign_key )] = item
133+ # Convert foreign key to string to ensure consistent key types
134+ key = str (getattr (item , self .foreign_key ))
135+ mapped [key ] = item
126136 return mapped
127137
128138 def attach (self , current_model , related_record ):
0 commit comments