Exemplo n.º 1
0
        def fdel(model_self):
            identity_values = model_self.get_identity_entries(self.identity)

            if not identity_values['context']:
                raise FieldException('No valid context')

            if identity_values['context'] == identity_values['fallback']:
                raise FieldException(
                    'It is forbidden to remove entry on the fallback')

            o2m = identity_values['one2many']
            entry = o2m.filter_by(**identity_values['filter']).one_or_none()
            if entry is not None:
                setattr(entry, self.fieldname, None)
Exemplo n.º 2
0
        def fexpr(cls):
            res = cls.define_contextual_models()[self.identity]
            context_adapter = res.get('context_adapter', lambda x: x)
            context = context_adapter(
                cls.context.get(res.get('context', self.identity)))

            if not context:
                raise FieldException('No valid context')

            Model = getattr(cls, self.identity.capitalize())

            filters = [getattr(Model, self.identity) == context]
            relate_filters = [
                getattr(Model, x) == getattr(cls, x[len('relate_'):])
                for x in Model.loaded_columns if x.startswith("relate_")
            ]
            filters.extend(relate_filters)

            if res.get('fallback'):
                fallback_adapter = res.get('fallback_adapter', lambda x: x)
                fallback = fallback_adapter(res['fallback'])
                if fallback != context:
                    filters = or_(
                        and_(*filters),
                        and_(
                            getattr(Model, self.identity) == fallback,
                            *relate_filters,
                        ),
                    )
                    return select(getattr(
                        Model, self.fieldname)).filter(filters).limit(1).label(
                            self.fieldname)

            return select(getattr(Model, self.fieldname)).filter(
                and_(*filters)).limit(1).label(self.fieldname)
Exemplo n.º 3
0
    def insert(cls, **kwargs):
        contextual = {}
        values = kwargs.copy()

        lnfs = cls.anyblok.loaded_namespaces_first_step[cls.__registry_name__]
        for field in kwargs:
            if field in cls.loaded_contextual_fields:
                if lnfs[field].identity not in contextual:
                    contextual[lnfs[field].identity] = {}

                contextual[lnfs[field].identity][field] = values.pop(field)

        res = super(ContextualMixin, cls).insert(**values)

        for identity, values in contextual.items():
            identity_values = res.get_identity_entries(identity)
            if not identity_values['context']:
                raise FieldException('No valid context')

            values.update({identity: identity_values['context']})
            getattr(cls, identity.capitalize()).insert(relate=res, **values)
            if identity_values['fallback']:
                if identity_values['fallback'] != identity_values['context']:
                    values.update({identity: identity_values['fallback']})
                    getattr(cls, identity.capitalize()).insert(relate=res,
                                                               **values)

        return res
Exemplo n.º 4
0
    def __init__(self, field=None, identity=None):
        self.field = field
        self.identity = identity

        for f in ['field', 'identity']:
            if getattr(self, f) is None:
                raise FieldException(
                    f"'{f}' is a required attribute for Contextual")

        if isinstance(self.field,
                      (Function, Sequence, One2One, One2Many, Many2Many)):
            raise FieldException(f"'{f}' could not be {self.field.__class__}")

        if (isinstance(self.field, Many2One)
                and self.field.kwargs.get('backref')):
            raise FieldException(f"'{f}' could not have one2many attribute")

        super(Contextual, self).__init__()
Exemplo n.º 5
0
        def fset(model_self, value):
            identity_values = model_self.get_identity_entries(self.identity)

            if not identity_values['context']:
                raise FieldException('No valid context')

            o2m = identity_values['one2many']
            entry = o2m.filter_by(**identity_values['filter']).one_or_none()

            if entry is None:
                values = {
                    self.fieldname: value,
                    'relate': model_self,
                }
                values.update(identity_values['filter'])
                entry = identity_values['Model'](**values)
                model_self.anyblok.session.add(entry)

            else:
                entry.update(**{self.fieldname: value})
Exemplo n.º 6
0
        def fget(model_self):
            identity_values = model_self.get_identity_entries(self.identity)

            if not identity_values['context']:
                raise FieldException('No valid context')

            o2m = identity_values['one2many']
            entry = o2m.filter_by(**identity_values['filter']).one_or_none()

            if entry is None:
                if not identity_values['fallback']:
                    return identity_values['Model'].get_default_values().get(
                        self.fieldname)

                if identity_values['fallback'] != identity_values['context']:
                    entry = o2m.filter_by(
                        **identity_values['filter_fallback']).one_or_none()
                    if entry is None:
                        return identity_values['Model'].get_default_values(
                        ).get(self.fieldname)

            return getattr(entry, self.fieldname)
Exemplo n.º 7
0
        def fcomparator(cls):
            res = cls.define_contextual_models()[self.identity]
            context_adapter = res.get('context_adapter', lambda x: x)
            context = context_adapter(
                cls.context.get(res.get('context', self.identity)))

            if not context:
                raise FieldException('No valid context')

            Model = getattr(cls, self.identity.capitalize())

            filters = [getattr(Model, self.identity) == context]
            filters.extend([
                getattr(Model, x) == getattr(cls, x[len('relate_'):])
                for x in Model.loaded_columns if x.startswith("relate_")
            ])

            fields = [(x, x[len(self.fieldname) + 1:])
                      for x in Model.loaded_columns
                      if x.startswith(f'{self.fieldname}_')]

            expr = select(Model).filter(and_(*filters)).limit(1)

            return Many2OneComparator(fields, expr)