Exemplo n.º 1
0
 def __init__(self, proj_sig, app_name, model_name, model_sig, stub=False,
              db_name=None):
     self.app_name = app_name
     self.model_name = model_name
     self._meta = MockMeta(proj_sig, app_name, model_name, model_sig)
     self._meta.setup_fields(self, stub)
     self._state = ModelState(db_name)
Exemplo n.º 2
0
    def __init__(self, area):
        self._state = ModelState()
        self.id = self.pk = area.pk
        self.api_id = area.api_id
        self.name = area.name
        for attr_name, attr_value in six.iteritems(area.__dict__):
            if attr_name.startswith('_name_'):
                setattr(self, attr_name, attr_value)

        self.included_countries = frozenset(
            country.pk for country in area.included_countries.all())
        self.included_country_codes = frozenset(
            country.code for country in area.included_countries.all())
        self.excluded_countries = frozenset(
            country.pk for country in area.excluded_countries.all())
        self.excluded_country_codes = frozenset(
            country.code for country in area.excluded_countries.all())
        self.included_subdivisions = frozenset(
            subdivision.pk for subdivision in area.included_subdivisions.all())
        self.included_subdivision_codes = frozenset(
            subdivision.code
            for subdivision in area.included_subdivisions.all())
        self.excluded_subdivisions = frozenset(
            subdivision.pk for subdivision in area.excluded_subdivisions.all())
        self.excluded_subdivision_codes = frozenset(
            subdivision.code
            for subdivision in area.excluded_subdivisions.all())
Exemplo n.º 3
0
class Model(object):
    _deferred = False
    _state = ModelState()

    class DoesNotExist(Exception):
        pass

    def __init__(self, *args, **kwargs):
        if self.adapter.fields_defaults:
            self.__dict__.update(self.adapter.fields_defaults)

        for i, arg in enumerate(args):
            field_name = self.adapter.fields[i]

            setattr(self, field_name, arg)

        self.__dict__.update(kwargs)

        keys = set(self.__dict__.keys())
        for name in self.adapter.fields:
            if name not in keys:
                setattr(self, name, None)

    def __unicode__(self):
        return self.adapter.to_unicode(self)

    def save(self):
        self.adapter.put(self)

    def delete(self):
        self.adapter.delete(self)

    def _get_pk_val(self):
        if not getattr(self, '_pk_cache', None):
            self._pk_cache = self.adapter.id(self)
        return self._pk_cache

    def _set_pk_val(self, val):
        self._pk_cache = val

    pk = property(_get_pk_val, _set_pk_val)

    def serializable_value(self, field_name):
        getattr(self, field_name)

    def clean_fields(self, exclude=None):
        pass

    def clean(self):
        pass

    def _get_unique_checks(self, exclude=None):
        return [], []

    def validate_unique(self, exclude=None):
        pass

    def _collect_sub_objects(self, collector):
        pass
Exemplo n.º 4
0
    def __init__(self,
                 project_sig,
                 app_name,
                 model_name,
                 model_sig,
                 auto_created=False,
                 managed=False,
                 stub=False,
                 db_name=None):
        """Initialize the model.

        Args:
            project_sig (django_evolution.signature.ProjectSignature):
                The project's schema signature.

            app_name (unicode):
                The name of the Django app that owns the model.

            model_name (unicode):
                The name of the model.

            model_sig (dict):
                The model's schema signature.

            auto_created (bool, optional):
                Whether this represents an auto-created model (such as an
                intermediary many-to-many model).

            managed (bool, optional):
                Whether this represents a model managed internally by Django,
                rather than a developer-created model.

            stub (bool, optional):
                Whether this is a stub model. This is used internally to
                create models that only contain a primary key field and no
                others, for use when dealing with circular relationships.

            db_name (unicode, optional):
                The name of the database where the model would be read from or
                written to.
        """
        assert model_sig, \
            'model_sig for %s.%s cannot be None!' % (app_name, model_name)

        self.app_name = app_name
        self.model_name = model_name
        self._meta = MockMeta(project_sig=project_sig,
                              app_name=app_name,
                              model_name=model_name,
                              model_sig=model_sig,
                              auto_created=auto_created,
                              managed=managed)
        self._meta.setup_fields(self, stub)

        self._state = ModelState()
        self._state.db = db_name
Exemplo n.º 5
0
    def __init__(self, *args, **kwargs):
        if 'deleted' in kwargs:
            raise ValueError("deleted property is reserved for neomodel")

        for key, val in self.__all_relationships__:
            self.__dict__[key] = val.build_manager(self, key)

        self._state = ModelState()

        super(StructuredNode, self).__init__(*args, **kwargs)
Exemplo n.º 6
0
class BaseModel(object, metaclass=Constructor):
    _deferred = False
    _state = ModelState()
    objects = None  #IDE Autocompletion

    class DoesNotExist(ObjectDoesNotExist):
        pass

    class MultipleObjectsReturned(ObjectDoesNotExist):
        pass

    class Meta:
        pass
Exemplo n.º 7
0
    def _build_fields_modifs(cls, instance):
        modifs = []
        backup = getattr(instance, '_instance_backup', None)

        if backup is not None:
            backup['_state'] = ModelState()
            old_instance = instance.__class__()
            old_instance.__dict__ = backup
            excluded_fields = _EXCLUDED_FIELDS if isinstance(
                instance, CremeEntity) else ()

            for field in instance._meta.fields:
                fname = field.name

                if fname in excluded_fields or not field.get_tag('viewable'):
                    continue

                old_value = getattr(old_instance, fname)
                new_value = getattr(instance, fname)

                if isinstance(field, ForeignKey):
                    old_value = old_value and old_value.pk
                    new_value = new_value and new_value.pk
                else:
                    try:
                        # Sometimes a form sets a unicode representing an int in an IntegerField (for example)
                        # => the type difference leads to a useless log like: Set field “My field” from “X” to “X”
                        new_value = field.clean(new_value, instance)
                    except ValidationError as e:
                        logger.debug(
                            'Error in _HistoryLineType._build_fields_modifs() [%s]: %s',
                            __name__, e)
                        continue

                if old_value != new_value:
                    if not new_value and not old_value:  # Ignore useless changes like : None -> ""
                        continue

                    if field.get_internal_type() not in _SERIALISABLE_FIELDS:
                        modif = (fname, )
                    elif old_value:
                        modif = (fname, old_value, new_value)
                    else:
                        modif = (fname, new_value)

                    modifs.append(modif)

        return modifs
Exemplo n.º 8
0
def model_unpickle(model, vector, db, adding, _cache={}):
    try:
        cls = _cache[model]
    except KeyError:
        # Only needed in Django 1.8 and 1.9
        if not apps.ready:
            apps.populate(settings.INSTALLED_APPS)
        cls = _cache[model] = apps.get_model(*model.split('.'))
    obj = cls.__new__(cls)
    obj.__dict__.update(izip(attnames(cls), vector))

    # Restore state. This is the fastest way to create object I know.
    obj._state = ModelState.__new__(ModelState)
    obj._state.__dict__ = {'db': db, 'adding': adding}

    return obj
Exemplo n.º 9
0
def model_unpickle(model, vector, db, adding, _cache={}):
    try:
        cls = _cache[model]
    except KeyError:
        # Only needed in Django 1.8 and 1.9
        if not apps.ready:
            apps.populate(settings.INSTALLED_APPS)
        cls = _cache[model] = apps.get_model(*model.split('.'))
    obj = cls.__new__(cls)
    obj.__dict__.update(izip(attnames(cls), vector))

    # Restore state. This is the fastest way to create object I know.
    obj._state = ModelState.__new__(ModelState)
    obj._state.__dict__ = {'db': db, 'adding': adding}

    return obj
Exemplo n.º 10
0
class ServiceModel(with_metaclass(constructor)):
    _deferred = False
    _state = ModelState()

    def __unicode__(self):
        return self.id

    def serializable_value(self, field_name):
        try:
            field = self._meta.get_field(field_name)
        except FieldDoesNotExist:
            return getattr(self, field_name)
        return getattr(self, field.attname)

    @property
    def pk(self):
        return self.id

        # klass.objects = klass._default_manager

    def __eq__(self, other):
        if isinstance(other, ServiceModel):
            return self.pk == other.pk
        return False

    def full_clean(self, *args, **kwargs):
        pass

    def validate_unique(self, *args, **kwargs):
        pass

    def _get_unique_checks(self, *args, **kwargs):
        return (
            [],
            [],
        )

    def _get_pk_val(self):
        return None

    def save(self, *args, **kwargs):
        fields = [a.name for a in self._meta.get_fields()]
        data = {}
        for field in fields:
            data.update({field: getattr(self, field)})
        return self.objects.get_queryset().create(**data)
Exemplo n.º 11
0
    def __init__(self, *args, **kwargs):
        # super(NodbModel, self).__init__(*args, **kwargs)
        self._state = ModelState()

        self.__dict__.update(kwargs)

        # We need to trigger the __set__ method of related fields
        for (key, value) in kwargs.iteritems():
            if key in self.__class__.__dict__ and \
                    isinstance(self.__class__.__dict__[key], ReverseSingleRelatedObjectDescriptor):
                setattr(self, key, value)

        for field in self._meta.concrete_fields:
            is_related_field = isinstance(field.rel, ForeignObjectRel)

            # set defaults:
            if not is_related_field \
                    and not self.attribute_is_unevaluated_lazy_property(field.name) \
                    and not hasattr(self, field.name):
                setattr(self, field.name, field.get_default())
Exemplo n.º 12
0
 def __init__(self, *args, **kwargs):
     self._state = ModelState()
     self._state.db = self._meta.get("db_alias", me.DEFAULT_CONNECTION_NAME)
     super(DjangoFlavor, self).__init__(*args, **kwargs)
Exemplo n.º 13
0
    def __init__(self, *args, **kwargs):
        # Alias some things as locals to avoid repeat global lookups
        cls = self.__class__
        opts = self._meta
        _setattr = setattr
        _DEFERRED = DEFERRED

        pre_init.send(sender=cls, args=args, kwargs=kwargs)

        # Set up the storage for instance state
        self._state = ModelState()

        # There is a rather weird disparity here; if kwargs, it's set, then args
        # overrides it. It should be one or the other; don't duplicate the work
        # The reason for the kwargs check is that standard iterator passes in by
        # args, and instantiation for iteration is 33% faster.
        if len(args) > len(opts.concrete_fields):
            # Daft, but matches old exception sans the err msg.
            raise IndexError("Number of args exceeds number of fields")

        if not kwargs:
            fields_iter = iter(opts.concrete_fields)
            # The ordering of the zip calls matter - zip throws StopIteration
            # when an iter throws it. So if the first iter throws it, the second
            # is *not* consumed. We rely on this, so don't change the order
            # without changing the logic.
            for val, field in zip(args, fields_iter):
                if val is _DEFERRED:
                    continue
                _setattr(self, field.attname, val)
        else:
            # Slower, kwargs-ready version.
            fields_iter = iter(opts.fields)
            for val, field in zip(args, fields_iter):
                if val is _DEFERRED:
                    continue
                _setattr(self, field.attname, val)
                kwargs.pop(field.name, None)

        # Now we're left with the unprocessed fields that *must* come from
        # keywords, or default.

        for field in fields_iter:
            is_related_object = False
            # Virtual field
            if field.attname not in kwargs and field.column is None:
                continue
            if kwargs:
                if isinstance(field.remote_field, ForeignObjectRel):
                    try:
                        # Assume object instance was passed in.
                        rel_obj = kwargs.pop(field.name)
                        is_related_object = True
                    except KeyError:
                        try:
                            # Object instance wasn't passed in -- must be an ID.
                            val = kwargs.pop(field.attname)
                        except KeyError:
                            val = field.get_default()
                    else:
                        # Object instance was passed in. Special case: You can
                        # pass in "None" for related objects if it's allowed.
                        if rel_obj is None and field.null:
                            val = None
                else:
                    try:
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        # This is done with an exception rather than the
                        # default argument on pop because we don't want
                        # get_default() to be evaluated, and then not used.
                        # Refs #12057.
                        val = field.get_default()
            else:
                val = field.get_default()

            if is_related_object:
                # If we are passed a related instance, set it using the
                # field.name instead of field.attname (e.g. "user" instead of
                # "user_id") so that the object gets properly cached (and type
                # checked) by the RelatedObjectDescriptor.
                if rel_obj is not _DEFERRED:
                    _setattr(self, field.name, rel_obj)
            else:
                if val is not _DEFERRED:
                    _setattr(self, field.attname, val)

        if kwargs:
            property_names = opts._property_names
            for prop in tuple(kwargs):
                try:
                    # Any remaining kwargs must correspond to properties or
                    # virtual fields.
                    if prop in property_names or opts.get_field(prop):
                        if kwargs[prop] is not _DEFERRED:
                            _setattr(self, prop, kwargs[prop])
                        del kwargs[prop]
                except (AttributeError, FieldDoesNotExist):
                    pass
            if kwargs:
                for key, value in kwargs.items():
                    if hasattr(self, key):
                        raise TypeError(
                            "'%s' is an invalid keyword argument for this function"
                            % key)

                    setattr(self, key, value)
        super(Model, self).__init__()
        post_init.send(sender=cls, instance=self)