@@ -118,8 +118,8 @@ def __repr__(self):
118118
119119class Field (object ):
120120 """The class for defining pyArango fields."""
121- def __init__ (self , validators = None , default = "" ):
122- """validators must be a list of validators"""
121+ def __init__ (self , validators = None , default = None ):
122+ """validators must be a list of validators. default can also be a callable """
123123 if not validators :
124124 validators = []
125125 self .validators = validators
@@ -238,16 +238,6 @@ class Collection(with_metaclass(Collection_metaclass, object)):
238238
239239 def __init__ (self , database , jsonData ):
240240
241- def getDefaultDoc (fields , dct ):
242- for k , v in fields .items ():
243- if isinstance (v , dict ):
244- dct [k ] = getDefaultDoc (fields [k ], {})
245- elif isinstance (v , Field ):
246- dct [k ] = v .default
247- else :
248- raise ValueError ("Field '%s' is of invalid type '%s'" % (k , type (v )) )
249- return dct
250-
251241 self .database = database
252242 self .connection = self .database .connection
253243 self .name = self .__class__ .__name__
@@ -267,13 +257,30 @@ def getDefaultDoc(fields, dct):
267257 "fulltext" : {},
268258 }
269259 self .indexes_by_name = {}
270-
271- self .defaultDocument = getDefaultDoc (self ._fields , {})
260+ # self.defaultDocument = None #getDefaultDoc(self._fields, {})
272261 self ._isBulkInProgress = False
273262 self ._bulkSize = 0
274263 self ._bulkCache = []
275264 self ._bulkMode = BulkMode .NONE
276265
266+ def getDefaultDocument (self , fields = None , dct = None ):
267+ if dct is None :
268+ dct = {}
269+ if fields is None :
270+ fields = self ._fields
271+
272+ for k , v in fields .items ():
273+ if isinstance (v , dict ):
274+ dct [k ] = self .getDefaultDocument (fields [k ], None )
275+ elif isinstance (v , Field ):
276+ if callable (v .default ):
277+ dct [k ] = v .default ()
278+ else :
279+ dct [k ] = v .default
280+ else :
281+ raise ValueError ("Field '%s' is of invalid type '%s'" % (k , type (v )) )
282+ return dct
283+
277284 def getURL (self ):
278285 return "%s/collection/%s" % (self .database .getURL (), self .name )
279286
@@ -316,7 +323,9 @@ def delete(self):
316323
317324 def createDocument (self , initDict = None ):
318325 """create and returns a completely empty document or one populated with initDict"""
319- res = dict (self .defaultDocument )
326+ # res = dict(self.defaultDocument)
327+ res = self .getDefaultDocument ()
328+
320329 if initDict is not None :
321330 res .update (initDict )
322331
@@ -638,55 +647,6 @@ def validatePrivate(self, field, value):
638647 self ._fields [field ].validate (value )
639648 return True
640649
641- # @classmethod
642- # def validateField(cls, fieldName, value):
643- # """checks if 'value' is valid for field 'fieldName'. If the validation is unsuccessful, raises a SchemaViolation or a ValidationError.
644- # for nested dicts ex: {address : { street: xxx} }, fieldName can take the form address.street
645- # """
646-
647- # def _getValidators(cls, fieldName):
648- # path = fieldName.split(".")
649- # v = cls._fields
650- # for k in path:
651- # try:
652- # v = v[k]
653- # except KeyError:
654- # return None
655- # return v
656-
657- # field = _getValidators(cls, fieldName)
658-
659- # if field is None:
660- # if not cls._validation["allow_foreign_fields"]:
661- # raise SchemaViolation(cls, fieldName)
662- # else:
663- # return field.validate(value)
664-
665- # @classmethod
666- # def validateDct(cls, dct):
667- # "validates a dictionary. The dictionary must be defined such as {field: value}. If the validation is unsuccefull, raises an InvalidDocument"
668- # def _validate(dct, res, parentsStr=""):
669- # for k, v in dct.items():
670- # if len(parentsStr) == 0:
671- # ps = k
672- # else:
673- # ps = "%s.%s" % (parentsStr, k)
674-
675- # if type(v) is dict:
676- # _validate(v, res, ps)
677- # elif k not in cls.arangoPrivates:
678- # try:
679- # cls.validateField(ps, v)
680- # except (ValidationError, SchemaViolation) as e:
681- # res[k] = str(e)
682-
683- # res = {}
684- # _validate(dct, res)
685- # if len(res) > 0:
686- # raise InvalidDocument(res)
687-
688- # return True
689-
690650 @classmethod
691651 def hasField (cls , fieldName ):
692652 """returns True/False wether the collection has field K in it's schema. Use the dot notation for the nested fields: address.street"""
@@ -982,3 +942,4 @@ def __enter__(self):
982942 return self .coll
983943 def __exit__ (self , type , value , traceback ):
984944 self .coll ._finalizeBatch ();
945+
0 commit comments