1919from pynetbox .lib .query import Request
2020
2121
22- def _get_return (lookup , return_fields = [ 'id' , 'value' , 'nested_return' ] ):
22+ def get_return (lookup , return_fields = None ):
2323
24- for i in return_fields :
24+ for i in return_fields or [ 'id' , 'value' , 'nested_return' ] :
2525 if isinstance (lookup , dict ) and lookup .get (i ):
2626 return lookup [i ]
2727 else :
@@ -33,6 +33,13 @@ def _get_return(lookup, return_fields=['id', 'value', 'nested_return']):
3333 return lookup
3434
3535
36+ def flatten_custom (custom_dict ):
37+ return {
38+ k : v if not isinstance (v , dict ) else v ['value' ]
39+ for k , v in custom_dict .items ()
40+ }
41+
42+
3643class Record (object ):
3744 """Create python objects from netbox API responses.
3845
@@ -114,7 +121,7 @@ def _add_cache(self, item):
114121 self ._full_cache .append ((key , dict (value )))
115122 else :
116123 self ._full_cache .append ((key , value ))
117- self ._index_cache .append ((key , _get_return (value )))
124+ self ._index_cache .append ((key , get_return (value )))
118125
119126 def _parse_values (self , values ):
120127 """ Parses values init arg.
@@ -148,12 +155,11 @@ def _compare(self):
148155 init_vals = dict (self ._index_cache )
149156 for i in dict (self ):
150157 current_val = init_vals .get (i )
151- if i != 'custom_fields' :
152- if isinstance (current_val , dict ):
153- init_dict .update ({i : _get_return (current_val )})
154- else :
155- init_dict .update ({i : _get_return (current_val )})
156- init_dict .update ({i : current_val })
158+ if i == 'custom_fields' :
159+ init_dict [i ] = flatten_custom (current_val )
160+ else :
161+ init_dict [i ] = get_return (current_val )
162+
157163 if init_dict == self .serialize ():
158164 return True
159165 return False
@@ -193,18 +199,24 @@ def serialize(self, nested=False):
193199 :returns: dict of values the NetBox API is expecting.
194200 """
195201 if nested :
196- return _get_return (self )
202+ return get_return (self )
197203
198204 ret = {}
199205 for i in dict (self ):
200206 current_val = getattr (self , i )
201- if isinstance (current_val , Record ):
202- current_val = getattr (current_val , 'serialize' )(nested = True )
207+ if i == 'custom_fields' :
208+ ret [i ] = flatten_custom (current_val )
209+ else :
210+ if isinstance (current_val , Record ):
211+ current_val = getattr (
212+ current_val ,
213+ 'serialize'
214+ )(nested = True )
203215
204- if isinstance (current_val , netaddr .ip .IPNetwork ):
205- current_val = str (current_val )
216+ if isinstance (current_val , netaddr .ip .IPNetwork ):
217+ current_val = str (current_val )
206218
207- ret . update ({ i : current_val })
219+ ret [ i ] = current_val
208220 return ret
209221
210222 def save (self ):
0 commit comments