Exemple #1
0
    def finalize(self):
        """
        """
        self.flush_deferred_objects()

        if len(self.AFTER_LOAD_HANDLERS):
            logger.info(
                "Finalize %d after_load handlers",
                len(self.AFTER_LOAD_HANDLERS))

        for h in self.AFTER_LOAD_HANDLERS:
            logger.info("Running after_load handler %s", h.__doc__)
            h(self)

        logger.info("Loaded %d objects", self.count_objects)
    
        if self.save_later:
            count = 0
            s = ''
            for model, msg_objects in self.save_later.items():
                for msg, objects in msg_objects.items():
                    if False:  # detailed content of the first object
                        s += "\n- %s %s (%d object(s), e.g. %s)" % (
                            full_model_name(model), msg, len(objects),
                            obj2str(objects[0].object, force_detailed=True))
                    else:  # pk of all objects
                        s += "\n- %s %s (%d object(s) with primary key %s)" % (
                            full_model_name(model), msg, len(objects),
                            ', '.join([unicode(o.object.pk) for o in objects]))
                    count += len(objects)

            msg = "Abandoning with %d unsaved instances:%s" % (count, s)
            logger.warning(msg)
Exemple #2
0
 def register_failure(self, obj, e):
     msg = force_unicode(e)
     d = self.save_later.setdefault(obj.object.__class__, {})
     l = d.setdefault(msg, [])
     if len(l) == 0:
         logger.info("Deferred %s : %s", obj2str(obj.object), msg)
     l.append(obj)
Exemple #3
0
 def __repr__(self):
     s = self.__class__.__name__+"("
     attrs = []
     for k in 'label instance bound_action href params name'.split():
         v = getattr(self,k)
         if v is not None:
             attrs.append(k+"="+obj2str(v))
     s += ', '.join(attrs)
     return s+")"
Exemple #4
0
 def try_save(self, *args, **kw):
     """Try to save the specified Model instance `obj`. Return `True`
     on success, `False` if this instance wasn't saved and should be
     deferred.
     """
     obj = self.object
     try:
         """
         """
         m = getattr(obj, 'before_dumpy_save', None)
         if m is not None:
             m()
         if not self.deserializer.quick:
             obj.full_clean()
         obj.save(*args, **kw)
         logger.debug("%s has been saved" % obj2str(obj))
         self.deserializer.register_success()
         return True
     #~ except ValidationError,e:
     #~ except ObjectDoesNotExist,e:
     #~ except (ValidationError,ObjectDoesNotExist), e:
     #~ except (ValidationError,ObjectDoesNotExist,IntegrityError), e:
     except Exception, e:
         if True:
             if not settings.SITE.loading_from_dump:
                 # hand-written fixtures are expected to yield in savable
                 # order
                 logger.warning("Failed to save %s:" % obj2str(obj))
                 raise
         deps = [f.rel.to for f in obj._meta.fields if f.rel is not None]
         if not deps:
             logger.exception(e)
             raise Exception(
                 "Failed to save independent %s." % obj2str(obj))
         self.deserializer.register_failure(self, e)
         return False
Exemple #5
0
    def lookup_or_create(model, lookup_field, value, **known_values):
        """
        Look-up whether there is a model instance having 
        `lookup_field` with value `value`
        (and optionally other `known_values` matching exactly).
        
        If it doesn't exist, create it and emit an 
        :attr:`auto_create <lino.core.signals.auto_create>` signal.
        
        """
        #~ logger.info("2013011 lookup_or_create")
        fkw = dict()
        fkw.update(known_values)

        if isinstance(lookup_field, basestring):
            lookup_field = model._meta.get_field(lookup_field)
        if isinstance(lookup_field, dbutils.BabelCharField):
            flt = dbutils.lookup_filter(
                lookup_field.name, value, **known_values)
        else:
            if isinstance(lookup_field, models.CharField):
                fkw[lookup_field.name + '__iexact'] = value
            else:
                fkw[lookup_field.name] = value
            flt = models.Q(**fkw)
            #~ flt = models.Q(**{self.lookup_field.name: value})
        qs = model.objects.filter(flt)
        if qs.count() > 0:  # if there are multiple objects, return the first
            if qs.count() > 1:
                logger.warning(
                    "%d %s instances having %s=%r (I'll return the first).",
                    qs.count(), model.__name__, lookup_field.name, value)
            return qs[0]
        #~ known_values[lookup_field.name] = value
        obj = model(**known_values)
        setattr(obj, lookup_field.name, value)
        try:
            obj.full_clean()
        except ValidationError, e:
            raise ValidationError("Failed to auto_create %s : %s" %
                                  (obj2str(obj), e))
Exemple #6
0
 def __repr__(self):
     return obj2str(self)