Python django.core.exceptions.FieldError() Examples

The following are code examples for showing how to use django.core.exceptions.FieldError(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: cerberus-core   Author: ovh   File: TicketsController.py    (license) View Source Project 7 votes vote down vote up
def add_tag(ticket_id, body, user):
    """ Add ticket tag
    """
    try:
        tag = Tag.objects.get(**body)
        ticket = Ticket.objects.get(id=ticket_id)

        if ticket.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for ticket')

        ticket.tags.add(tag)
        ticket.save()
        database.log_action_on_ticket(
            ticket=ticket,
            action='add_tag',
            user=user,
            tag_name=tag.name
        )
    except MultipleObjectsReturned:
        raise BadRequest('Please use tag id')
    except (KeyError, FieldError, IntegrityError, ObjectDoesNotExist, ValueError):
        raise NotFound('Tag or ticket not found')
    return {'message': 'Tag successfully added'} 
Example 2
Project: CodingDojo   Author: ComputerSocietyUNB   File: operations.py    (license) View Source Project 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        )
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass 
Example 3
Project: CodingDojo   Author: ComputerSocietyUNB   File: query.py    (license) View Source Project 6 votes vote down vote up
def solve_lookup_type(self, lookup):
        """
        Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
        """
        lookup_splitted = lookup.split(LOOKUP_SEP)
        if self._annotations:
            expression, expression_lookups = refs_expression(lookup_splitted, self.annotations)
            if expression:
                return expression_lookups, (), expression
        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
        field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
        if len(lookup_parts) == 0:
            lookup_parts = ['exact']
        elif len(lookup_parts) > 1:
            if not field_parts:
                raise FieldError(
                    'Invalid lookup "%s" for model %s".' %
                    (lookup, self.get_meta().model.__name__))
        return lookup_parts, field_parts, False 
Example 4
Project: CodingDojo   Author: ComputerSocietyUNB   File: query.py    (license) View Source Project 6 votes vote down vote up
def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
        if not allow_joins and LOOKUP_SEP in name:
            raise FieldError("Joined field references are not permitted in this query")
        if name in self.annotations:
            if summarize:
                # Summarize currently means we are doing an aggregate() query
                # which is executed as a wrapped subquery if any of the
                # aggregate() elements reference an existing annotation. In
                # that case we need to return a Ref to the subquery's annotation.
                return Ref(name, self.annotation_select[name])
            else:
                return self.annotation_select[name]
        else:
            field_list = name.split(LOOKUP_SEP)
            field, sources, opts, join_list, path = self.setup_joins(
                field_list, self.get_meta(),
                self.get_initial_alias(), reuse)
            targets, _, join_list = self.trim_joins(sources, join_list, path)
            if len(targets) > 1:
                raise FieldError("Referencing multicolumn fields with F() objects "
                                 "isn't supported")
            if reuse is not None:
                reuse.update(join_list)
            col = targets[0].get_col(join_list[-1], sources[0])
            return col 
Example 5
Project: CodingDojo   Author: ComputerSocietyUNB   File: query.py    (license) View Source Project 6 votes vote down vote up
def add_ordering(self, *ordering):
        """
        Adds items from the 'ordering' sequence to the query's "order by"
        clause. These items are either field names (not column names) --
        possibly with a direction prefix ('-' or '?') -- or OrderBy
        expressions.

        If 'ordering' is empty, all ordering is cleared from the query.
        """
        errors = []
        for item in ordering:
            if not hasattr(item, 'resolve_expression') and not ORDER_PATTERN.match(item):
                errors.append(item)
            if getattr(item, 'contains_aggregate', False):
                raise FieldError(
                    'Using an aggregate in order_by() without also including '
                    'it in annotate() is not allowed: %s' % item
                )
        if errors:
            raise FieldError('Invalid order_by arguments: %s' % errors)
        if ordering:
            self.order_by.extend(ordering)
        else:
            self.default_ordering = False 
Example 6
Project: CodingDojo   Author: ComputerSocietyUNB   File: compiler.py    (license) View Source Project 6 votes vote down vote up
def prepare_value(self, field, value):
        """
        Prepare a value to be used in a query by resolving it if it is an
        expression and otherwise calling the field's get_db_prep_save().
        """
        if hasattr(value, 'resolve_expression'):
            value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
            # Don't allow values containing Col expressions. They refer to
            # existing columns on a row, but in the case of insert the row
            # doesn't exist yet.
            if value.contains_column_references:
                raise ValueError(
                    'Failed to insert expression "%s" on %s. F() expressions '
                    'can only be used to update, not to insert.' % (value, field)
                )
            if value.contains_aggregate:
                raise FieldError("Aggregate functions are not allowed in this query")
        else:
            value = field.get_db_prep_save(value, connection=self.connection)
        return value 
Example 7
Project: cerberus-core   Author: ovh   File: TagsController.py    (license) View Source Project 6 votes vote down vote up
def create(body):
    """ Create new tag
    """
    try:
        body.pop('id', None)
        if body.get('tagType') not in TAG_TYPE:
            raise BadRequest('Invalid or missing tag type')

        existing = [tag.lower() for tag in Tag.objects.all().values_list('name', flat=True)]
        if body['name'].lower().strip() in existing:
            raise BadRequest('Tag already exists')
        body['codename'] = body['name'].lower().replace(' ', '_')
        tag = Tag.objects.get_or_create(**body)[0]
    except (AttributeError, KeyError, FieldError, IntegrityError, ValueError):
        raise BadRequest('Invalid fields in body')
    return model_to_dict(tag) 
Example 8
Project: cerberus-core   Author: ovh   File: TagsController.py    (license) View Source Project 6 votes vote down vote up
def update(tag_id, body):
    """ Update category
    """
    try:
        tag = Tag.objects.get(id=tag_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Tag not found')
    try:
        body.pop('id', None)

        existing = Tag.objects.exclude(id=tag.id).values_list('name', flat=True)
        existing = [tg.lower() for tg in existing]
        if body['name'].lower().strip() in existing:
            raise BadRequest('Tag already exists')

        Tag.objects.filter(pk=tag.pk).update(**body)
        tag = Tag.objects.get(pk=tag.pk)
    except (AttributeError, KeyError, FieldError, IntegrityError, ValueError, TypeError):
        raise BadRequest('Invalid fields in body')
    return model_to_dict(tag) 
Example 9
Project: cerberus-core   Author: ovh   File: TicketsController.py    (license) View Source Project 6 votes vote down vote up
def _update_duration(ticket, data, user):
    """ Generic update for duration
    """
    try:
        key = data.keys()[0]
        previous = getattr(ticket, key)
        data[key.replace('Duration', 'Start')] = datetime.now()

        Ticket.objects.filter(pk=ticket.pk).update(**data)
        ticket = Ticket.objects.get(pk=ticket.pk)

        database.log_action_on_ticket(
            ticket=ticket,
            action='update_property',
            user=user,
            property=key.replace('Duration', ''),
            previous_value=str(timedelta(seconds=previous)),
            new_value=str(timedelta(seconds=getattr(ticket, key)))
        )

    except (FieldDoesNotExist, FieldError, IntegrityError, TypeError, ValueError) as ex:
        raise BadRequest(str(ex.message))

    return show(ticket.id, user) 
Example 10
Project: cerberus-core   Author: ovh   File: TicketsController.py    (license) View Source Project 6 votes vote down vote up
def update_proof(ticket_id, proof_id, body, user):
    """ Update proof
    """
    ticket = None
    try:
        ticket = Ticket.objects.get(id=ticket_id)
        Proof.objects.get(id=proof_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Not Found')

    try:
        body.pop('id', None)
        body.pop('ticket', None)
        ticket.proof.update(**body)
        ticket.save()
        database.log_action_on_ticket(
            ticket=ticket,
            action='update_proof',
            user=user
        )
    except (KeyError, FieldDoesNotExist, FieldError, IntegrityError, TypeError, ValueError) as ex:
        raise BadRequest(str(ex.message))
    return {'message': 'Proof successfully updated'} 
Example 11
Project: cerberus-core   Author: ovh   File: TicketsController.py    (license) View Source Project 6 votes vote down vote up
def remove_tag(ticket_id, tag_id, user):
    """ Remove ticket tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
        ticket = Ticket.objects.get(id=ticket_id)

        if ticket.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for ticket')

        ticket.tags.remove(tag)
        ticket.save()
        database.log_action_on_ticket(
            ticket=ticket,
            action='remove_tag',
            user=user,
            tag_name=tag.name
        )

    except (ObjectDoesNotExist, FieldError, IntegrityError, ValueError):
        raise NotFound('Not Found')
    return {'message': 'Tag successfully removed'} 
Example 12
Project: cerberus-core   Author: ovh   File: NewsController.py    (license) View Source Project 6 votes vote down vote up
def update(news_id, body, user):
    """ Update news
    """
    try:
        if user.is_superuser:
            news = News.objects.get(id=news_id)
        else:
            news = News.objects.get(id=news_id, author__id=user.id)
    except (ObjectDoesNotExist, ValueError):
        return NotFound('News not found')
    try:
        body = {k: v for k, v in body.iteritems() if k not in ['author', 'date', 'tags']}
        News.objects.filter(pk=news.pk).update(**body)
        news = News.objects.get(pk=news.pk)
    except (KeyError, FieldError, IntegrityError):
        raise BadRequest('Invalid fields in body')
    return model_to_dict(news) 
Example 13
Project: cerberus-core   Author: ovh   File: TemplatesController.py    (license) View Source Project 6 votes vote down vote up
def index(**kwargs):
    """ Main endpoint, get all templates
    """
    filters = {}

    if kwargs.get('filters'):
        try:
            filters = json.loads(unquote(unquote(kwargs['filters'])))
        except (ValueError, SyntaxError, TypeError) as ex:
            raise BadRequest(str(ex.message))
    try:
        where = generate_request_filter(filters)
    except (AttributeError, KeyError, IndexError, FieldError,
            SyntaxError, TypeError, ValueError) as ex:
        raise BadRequest(str(ex.message))

    try:
        templates = MailTemplate.objects.filter(where).order_by('name')
    except (AttributeError, KeyError, IndexError, FieldError,
            SyntaxError, TypeError, ValueError) as ex:
        raise BadRequest(str(ex.message))

    return [model_to_dict(t) for t in templates] 
Example 14
Project: cerberus-core   Author: ovh   File: TemplatesController.py    (license) View Source Project 6 votes vote down vote up
def generate_request_filter(filters):
    """ Generates filters from filter query string
    """
    where = [Q()]
    if 'where' in filters and len(filters['where']):
        try:
            keys = set(k for k in filters['where'])
            if 'in' in keys:
                for i in filters['where']['in']:
                    for key, val in i.iteritems():
                        where.append(reduce(operator.or_, [Q(**{key: i}) for i in val]))
            where = reduce(operator.and_, where)
        except (AttributeError, KeyError, FieldError, SyntaxError, ValueError) as ex:
            raise BadRequest(str(ex.message))
    else:
        where = reduce(operator.and_, where)
    return where 
Example 15
Project: cerberus-core   Author: ovh   File: ReportItemsController.py    (license) View Source Project 6 votes vote down vote up
def update(item_id, body, user):
    """
        Update a report item
    """
    try:
        item = ReportItem.objects.get(id=item_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Item not found')

    try:
        resp = __get_item_infos(body, user)
        ReportItem.objects.filter(pk=item.pk).update(**resp)
        item = ReportItem.objects.get(pk=item.pk)
        if resp['report'].ticket:
            database.log_action_on_ticket(
                ticket=resp['report'].ticket,
                action='update_item',
                user=user
            )
    except (AttributeError, FieldError, IntegrityError, KeyError, ObjectDoesNotExist):
        raise BadRequest('Invalid fields in body')
    return show(item_id) 
Example 16
Project: cerberus-core   Author: ovh   File: DefendantsController.py    (license) View Source Project 6 votes vote down vote up
def remove_tag(defendant_id, tag_id, user):
    """ Remove defendant tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
        defendant = Defendant.objects.get(id=defendant_id)

        for defendt in Defendant.objects.filter(customerId=defendant.customerId):
            defendt.tags.remove(tag)
            defendt.save()

            for ticket in defendt.ticketDefendant.all():
                database.log_action_on_ticket(
                    ticket=ticket,
                    action='remove_tag',
                    user=user,
                    tag_name=tag.name
                )

    except (ObjectDoesNotExist, FieldError, IntegrityError, ValueError):
        raise NotFound('Defendant or tag not found')

    return show(defendant_id) 
Example 17
Project: cerberus-core   Author: ovh   File: ProvidersController.py    (license) View Source Project 6 votes vote down vote up
def create(body):
    """ Create provider
    """
    if 'email' not in body:
        raise BadRequest('Email field required')
    if len(Provider.objects.filter(email=body['email'])) > 1:
        raise BadRequest('Provider already exists')

    try:
        cat = None
        if body.get('defaultCategory'):
            cat = Category.objects.get(name=body['defaultCategory'])
        body.pop('defaultCategory', None)
        body = {k: v for k, v in body.iteritems() if k in PROVIDER_FIELDS}
        provider = Provider.objects.create(defaultCategory=cat, **body)
        return model_to_dict(provider)
    except (FieldError, IntegrityError, ObjectDoesNotExist) as ex:
        raise BadRequest(str(ex.message)) 
Example 18
Project: cerberus-core   Author: ovh   File: ProvidersController.py    (license) View Source Project 6 votes vote down vote up
def add_tag(provider_email, body):
    """ Add provider tag
    """
    try:
        tag = Tag.objects.get(**body)
        provider = Provider.objects.get(email=provider_email)

        if provider.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for provider')

        provider.tags.add(tag)
        provider.save()

    except (KeyError, FieldError, IntegrityError, ObjectDoesNotExist, ValueError):
        raise NotFound('Provider or tag not found')
    return model_to_dict(provider) 
Example 19
Project: cerberus-core   Author: ovh   File: ProvidersController.py    (license) View Source Project 6 votes vote down vote up
def remove_tag(provider_email, tag_id):
    """ Remove defendant tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
        provider = Provider.objects.get(email=provider_email)

        if provider.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for provider')

        provider.tags.remove(tag)
        provider.save()

    except (ObjectDoesNotExist, FieldError, IntegrityError, ValueError):
        raise NotFound('Provider or tag not found')
    return model_to_dict(provider) 
Example 20
Project: cerberus-core   Author: ovh   File: ReportsController.py    (license) View Source Project 6 votes vote down vote up
def remove_tag(report_id, tag_id):
    """ Remove report tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
        report = Report.objects.get(id=report_id)

        if report.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for report')

        report.tags.remove(tag)
        report.save()

    except (ObjectDoesNotExist, FieldError, IntegrityError, ValueError):
        raise NotFound('Report or tag not found')
    return {'message': 'Tag successfully removed'} 
Example 21
Project: django-jsonattrs   Author: Cadasta   File: decorators.py    (license) View Source Project 6 votes vote down vote up
def fixup_instance(sender, **kwargs):
    instance = kwargs['instance']
    for f in instance._meta.fields:
        if isinstance(f, JSONAttributeField):
            fi = getattr(instance, f.name)
            if not isinstance(fi, JSONAttributes):
                setattr(instance, f.name, JSONAttributes(fi))
            fld = getattr(instance, f.name)
            fld._instance = instance
            if hasattr(instance, '_attr_field'):
                raise FieldError('multiple JSONAttributeField fields: '
                                 'only one is allowed per model!')
            instance._attr_field = fld
    if not hasattr(instance, '_attr_field'):
        raise FieldError('missing JSONAttributeField field in '
                         'fixup_instance decorator') 
Example 22
Project: djangoql   Author: ivelum   File: admin.py    (license) View Source Project 6 votes vote down vote up
def get_search_results(self, request, queryset, search_term):
        use_distinct = False
        if not search_term:
            return queryset, use_distinct
        try:
            return (
                apply_search(queryset, search_term, self.djangoql_schema),
                use_distinct,
            )
        except (DjangoQLError, ValueError, FieldError) as e:
            msg = text_type(e)
        except ValidationError as e:
            msg = e.messages[0]
        queryset = queryset.none()
        messages.add_message(request, messages.WARNING, msg)
        return queryset, use_distinct 
Example 23
Project: lifesoundtrack   Author: MTG   File: operations.py    (license) View Source Project 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        )
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass 
Example 24
Project: lifesoundtrack   Author: MTG   File: subqueries.py    (license) View Source Project 6 votes vote down vote up
def add_update_values(self, values):
        """
        Convert a dictionary of field name to value mappings into an update
        query. This is the entry point for the public update() method on
        querysets.
        """
        values_seq = []
        for name, val in six.iteritems(values):
            field = self.get_meta().get_field(name)
            direct = not (field.auto_created and not field.concrete) or not field.concrete
            model = field.model._meta.concrete_model
            if not direct or (field.is_relation and field.many_to_many):
                raise FieldError(
                    'Cannot update model field %r (only non-relations and '
                    'foreign keys permitted).' % field
                )
            if model is not self.get_meta().model:
                self.add_related_update(model, field, val)
                continue
            values_seq.append((field, model, val))
        return self.add_update_fields(values_seq) 
Example 25
Project: lifesoundtrack   Author: MTG   File: query.py    (license) View Source Project 6 votes vote down vote up
def solve_lookup_type(self, lookup):
        """
        Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
        """
        lookup_splitted = lookup.split(LOOKUP_SEP)
        if self._annotations:
            expression, expression_lookups = refs_expression(lookup_splitted, self.annotations)
            if expression:
                return expression_lookups, (), expression
        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
        field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
        if len(lookup_parts) == 0:
            lookup_parts = ['exact']
        elif len(lookup_parts) > 1:
            if not field_parts:
                raise FieldError(
                    'Invalid lookup "%s" for model %s".' %
                    (lookup, self.get_meta().model.__name__))
        return lookup_parts, field_parts, False 
Example 26
Project: lifesoundtrack   Author: MTG   File: query.py    (license) View Source Project 6 votes vote down vote up
def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
        if not allow_joins and LOOKUP_SEP in name:
            raise FieldError("Joined field references are not permitted in this query")
        if name in self.annotations:
            if summarize:
                # Summarize currently means we are doing an aggregate() query
                # which is executed as a wrapped subquery if any of the
                # aggregate() elements reference an existing annotation. In
                # that case we need to return a Ref to the subquery's annotation.
                return Ref(name, self.annotation_select[name])
            else:
                return self.annotation_select[name]
        else:
            field_list = name.split(LOOKUP_SEP)
            field, sources, opts, join_list, path = self.setup_joins(
                field_list, self.get_meta(),
                self.get_initial_alias(), reuse)
            targets, _, join_list = self.trim_joins(sources, join_list, path)
            if len(targets) > 1:
                raise FieldError("Referencing multicolumn fields with F() objects "
                                 "isn't supported")
            if reuse is not None:
                reuse.update(join_list)
            col = targets[0].get_col(join_list[-1], sources[0])
            return col 
Example 27
Project: lifesoundtrack   Author: MTG   File: compiler.py    (license) View Source Project 6 votes vote down vote up
def prepare_value(self, field, value):
        """
        Prepare a value to be used in a query by resolving it if it is an
        expression and otherwise calling the field's get_db_prep_save().
        """
        if hasattr(value, 'resolve_expression'):
            value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
            # Don't allow values containing Col expressions. They refer to
            # existing columns on a row, but in the case of insert the row
            # doesn't exist yet.
            if value.contains_column_references:
                raise ValueError(
                    'Failed to insert expression "%s" on %s. F() expressions '
                    'can only be used to update, not to insert.' % (value, field)
                )
            if value.contains_aggregate:
                raise FieldError("Aggregate functions are not allowed in this query")
        else:
            value = field.get_db_prep_save(value, connection=self.connection)
        return value 
Example 28
Project: django-binder   Author: CodeYellowBV   File: views.py    (license) View Source Project 6 votes vote down vote up
def filter_deleted(self, queryset, pk, deleted, request):
		if pk:
			return queryset

		if deleted is None:
			try:
				return queryset.filter(deleted=False)
			except FieldError:
				return queryset

		if deleted == 'true':
			return queryset

		if deleted == 'only':
			try:
				return queryset.filter(deleted=True)
			except FieldError:
				raise BinderRequestError('This entity has no soft-delete attribute.')

		raise BinderRequestError('Invalid value: deleted={{{}}}.'.format(request.GET.get('deleted'))) 
Example 29
Project: django-binder   Author: CodeYellowBV   File: views.py    (license) View Source Project 6 votes vote down vote up
def filter_deleted(self, queryset, pk, deleted, request):
		if pk:
			return queryset

		if deleted is None:
			try:
				return queryset.filter(deleted=False)
			except FieldError:
				return queryset

		if deleted == 'true':
			return queryset

		if deleted == 'only':
			try:
				return queryset.filter(deleted=True)
			except FieldError:
				raise BinderRequestError('This entity has no soft-delete attribute.')

		raise BinderRequestError('Invalid value: deleted={{{}}}.'.format(request.GET.get('deleted'))) 
Example 30
Project: liberator   Author: libscie   File: operations.py    (license) View Source Project 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        )
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass 
Example 31
Project: liberator   Author: libscie   File: subqueries.py    (license) View Source Project 6 votes vote down vote up
def add_update_values(self, values):
        """
        Convert a dictionary of field name to value mappings into an update
        query. This is the entry point for the public update() method on
        querysets.
        """
        values_seq = []
        for name, val in six.iteritems(values):
            field = self.get_meta().get_field(name)
            direct = not (field.auto_created and not field.concrete) or not field.concrete
            model = field.model._meta.concrete_model
            if not direct or (field.is_relation and field.many_to_many):
                raise FieldError(
                    'Cannot update model field %r (only non-relations and '
                    'foreign keys permitted).' % field
                )
            if model is not self.get_meta().model:
                self.add_related_update(model, field, val)
                continue
            values_seq.append((field, model, val))
        return self.add_update_fields(values_seq) 
Example 32
Project: liberator   Author: libscie   File: query.py    (license) View Source Project 6 votes vote down vote up
def solve_lookup_type(self, lookup):
        """
        Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
        """
        lookup_splitted = lookup.split(LOOKUP_SEP)
        if self._annotations:
            expression, expression_lookups = refs_expression(lookup_splitted, self.annotations)
            if expression:
                return expression_lookups, (), expression
        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
        field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
        if len(lookup_parts) == 0:
            lookup_parts = ['exact']
        elif len(lookup_parts) > 1:
            if not field_parts:
                raise FieldError(
                    'Invalid lookup "%s" for model %s".' %
                    (lookup, self.get_meta().model.__name__))
        return lookup_parts, field_parts, False 
Example 33
Project: liberator   Author: libscie   File: query.py    (license) View Source Project 6 votes vote down vote up
def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
        if not allow_joins and LOOKUP_SEP in name:
            raise FieldError("Joined field references are not permitted in this query")
        if name in self.annotations:
            if summarize:
                # Summarize currently means we are doing an aggregate() query
                # which is executed as a wrapped subquery if any of the
                # aggregate() elements reference an existing annotation. In
                # that case we need to return a Ref to the subquery's annotation.
                return Ref(name, self.annotation_select[name])
            else:
                return self.annotation_select[name]
        else:
            field_list = name.split(LOOKUP_SEP)
            field, sources, opts, join_list, path = self.setup_joins(
                field_list, self.get_meta(),
                self.get_initial_alias(), reuse)
            targets, _, join_list = self.trim_joins(sources, join_list, path)
            if len(targets) > 1:
                raise FieldError("Referencing multicolumn fields with F() objects "
                                 "isn't supported")
            if reuse is not None:
                reuse.update(join_list)
            col = targets[0].get_col(join_list[-1], sources[0])
            return col 
Example 34
Project: liberator   Author: libscie   File: compiler.py    (license) View Source Project 6 votes vote down vote up
def prepare_value(self, field, value):
        """
        Prepare a value to be used in a query by resolving it if it is an
        expression and otherwise calling the field's get_db_prep_save().
        """
        if hasattr(value, 'resolve_expression'):
            value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
            # Don't allow values containing Col expressions. They refer to
            # existing columns on a row, but in the case of insert the row
            # doesn't exist yet.
            if value.contains_column_references:
                raise ValueError(
                    'Failed to insert expression "%s" on %s. F() expressions '
                    'can only be used to update, not to insert.' % (value, field)
                )
            if value.contains_aggregate:
                raise FieldError("Aggregate functions are not allowed in this query")
        else:
            value = field.get_db_prep_save(value, connection=self.connection)
        return value 
Example 35
Project: djanoDoc   Author: JustinChavez   File: operations.py    (license) View Source Project 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        )
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass 
Example 36
Project: djanoDoc   Author: JustinChavez   File: query.py    (license) View Source Project 6 votes vote down vote up
def solve_lookup_type(self, lookup):
        """
        Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
        """
        lookup_splitted = lookup.split(LOOKUP_SEP)
        if self._annotations:
            expression, expression_lookups = refs_expression(lookup_splitted, self.annotations)
            if expression:
                return expression_lookups, (), expression
        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
        field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
        if len(lookup_parts) == 0:
            lookup_parts = ['exact']
        elif len(lookup_parts) > 1:
            if not field_parts:
                raise FieldError(
                    'Invalid lookup "%s" for model %s".' %
                    (lookup, self.get_meta().model.__name__))
        return lookup_parts, field_parts, False 
Example 37
Project: djanoDoc   Author: JustinChavez   File: query.py    (license) View Source Project 6 votes vote down vote up
def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
        if not allow_joins and LOOKUP_SEP in name:
            raise FieldError("Joined field references are not permitted in this query")
        if name in self.annotations:
            if summarize:
                # Summarize currently means we are doing an aggregate() query
                # which is executed as a wrapped subquery if any of the
                # aggregate() elements reference an existing annotation. In
                # that case we need to return a Ref to the subquery's annotation.
                return Ref(name, self.annotation_select[name])
            else:
                return self.annotation_select[name]
        else:
            field_list = name.split(LOOKUP_SEP)
            field, sources, opts, join_list, path = self.setup_joins(
                field_list, self.get_meta(),
                self.get_initial_alias(), reuse)
            targets, _, join_list = self.trim_joins(sources, join_list, path)
            if len(targets) > 1:
                raise FieldError("Referencing multicolumn fields with F() objects "
                                 "isn't supported")
            if reuse is not None:
                reuse.update(join_list)
            col = targets[0].get_col(join_list[-1], sources[0])
            return col 
Example 38
Project: djanoDoc   Author: JustinChavez   File: query.py    (license) View Source Project 6 votes vote down vote up
def add_ordering(self, *ordering):
        """
        Adds items from the 'ordering' sequence to the query's "order by"
        clause. These items are either field names (not column names) --
        possibly with a direction prefix ('-' or '?') -- or OrderBy
        expressions.

        If 'ordering' is empty, all ordering is cleared from the query.
        """
        errors = []
        for item in ordering:
            if not hasattr(item, 'resolve_expression') and not ORDER_PATTERN.match(item):
                errors.append(item)
            if getattr(item, 'contains_aggregate', False):
                raise FieldError(
                    'Using an aggregate in order_by() without also including '
                    'it in annotate() is not allowed: %s' % item
                )
        if errors:
            raise FieldError('Invalid order_by arguments: %s' % errors)
        if ordering:
            self.order_by.extend(ordering)
        else:
            self.default_ordering = False 
Example 39
Project: djanoDoc   Author: JustinChavez   File: compiler.py    (license) View Source Project 6 votes vote down vote up
def prepare_value(self, field, value):
        """
        Prepare a value to be used in a query by resolving it if it is an
        expression and otherwise calling the field's get_db_prep_save().
        """
        if hasattr(value, 'resolve_expression'):
            value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
            # Don't allow values containing Col expressions. They refer to
            # existing columns on a row, but in the case of insert the row
            # doesn't exist yet.
            if value.contains_column_references:
                raise ValueError(
                    'Failed to insert expression "%s" on %s. F() expressions '
                    'can only be used to update, not to insert.' % (value, field)
                )
            if value.contains_aggregate:
                raise FieldError("Aggregate functions are not allowed in this query")
        else:
            value = field.get_db_prep_save(value, connection=self.connection)
        return value 
Example 40
Project: foundation   Author: altio   File: form.py    (license) View Source Project 6 votes vote down vote up
def get_form_class(self, obj=None, modelform_class=None, **kwargs):
        """
        Returns a Form class for use in the add/edit views.
        """
        # form will have been passed by an upstream call to get_formset_class
        # so if it is missing, this must be a single-object view on a non-inline
        # controller
        if modelform_class is None:
            modelform_class = self.modelform_class
        form_class_kwargs = self.get_form_class_kwargs(
            modelform_class=modelform_class, obj=obj, **kwargs)

        try:
            ModelForm = forms.modelform_factory(self.model, **form_class_kwargs)
        except FieldError as e:
            raise FieldError(
                '%s. Check fields/fieldsets/exclude attributes of class %s.'
                % (e, self.__class__.__name__)
            )
        return ModelForm 
Example 41
Project: django-next-train   Author: bitpixdigital   File: operations.py    (license) View Source Project 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        )
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass 
Example 42
Project: django-next-train   Author: bitpixdigital   File: query.py    (license) View Source Project 6 votes vote down vote up
def solve_lookup_type(self, lookup):
        """
        Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
        """
        lookup_splitted = lookup.split(LOOKUP_SEP)
        if self._annotations:
            expression, expression_lookups = refs_expression(lookup_splitted, self.annotations)
            if expression:
                return expression_lookups, (), expression
        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
        field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
        if len(lookup_parts) == 0:
            lookup_parts = ['exact']
        elif len(lookup_parts) > 1:
            if not field_parts:
                raise FieldError(
                    'Invalid lookup "%s" for model %s".' %
                    (lookup, self.get_meta().model.__name__))
        return lookup_parts, field_parts, False 
Example 43
Project: django-next-train   Author: bitpixdigital   File: query.py    (license) View Source Project 6 votes vote down vote up
def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
        if not allow_joins and LOOKUP_SEP in name:
            raise FieldError("Joined field references are not permitted in this query")
        if name in self.annotations:
            if summarize:
                # Summarize currently means we are doing an aggregate() query
                # which is executed as a wrapped subquery if any of the
                # aggregate() elements reference an existing annotation. In
                # that case we need to return a Ref to the subquery's annotation.
                return Ref(name, self.annotation_select[name])
            else:
                return self.annotation_select[name]
        else:
            field_list = name.split(LOOKUP_SEP)
            field, sources, opts, join_list, path = self.setup_joins(
                field_list, self.get_meta(),
                self.get_initial_alias(), reuse)
            targets, _, join_list = self.trim_joins(sources, join_list, path)
            if len(targets) > 1:
                raise FieldError("Referencing multicolumn fields with F() objects "
                                 "isn't supported")
            if reuse is not None:
                reuse.update(join_list)
            col = targets[0].get_col(join_list[-1], sources[0])
            return col 
Example 44
Project: django-next-train   Author: bitpixdigital   File: query.py    (license) View Source Project 6 votes vote down vote up
def add_ordering(self, *ordering):
        """
        Adds items from the 'ordering' sequence to the query's "order by"
        clause. These items are either field names (not column names) --
        possibly with a direction prefix ('-' or '?') -- or OrderBy
        expressions.

        If 'ordering' is empty, all ordering is cleared from the query.
        """
        errors = []
        for item in ordering:
            if not hasattr(item, 'resolve_expression') and not ORDER_PATTERN.match(item):
                errors.append(item)
            if getattr(item, 'contains_aggregate', False):
                raise FieldError(
                    'Using an aggregate in order_by() without also including '
                    'it in annotate() is not allowed: %s' % item
                )
        if errors:
            raise FieldError('Invalid order_by arguments: %s' % errors)
        if ordering:
            self.order_by.extend(ordering)
        else:
            self.default_ordering = False 
Example 45
Project: django-next-train   Author: bitpixdigital   File: compiler.py    (license) View Source Project 6 votes vote down vote up
def prepare_value(self, field, value):
        """
        Prepare a value to be used in a query by resolving it if it is an
        expression and otherwise calling the field's get_db_prep_save().
        """
        if hasattr(value, 'resolve_expression'):
            value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
            # Don't allow values containing Col expressions. They refer to
            # existing columns on a row, but in the case of insert the row
            # doesn't exist yet.
            if value.contains_column_references:
                raise ValueError(
                    'Failed to insert expression "%s" on %s. F() expressions '
                    'can only be used to update, not to insert.' % (value, field)
                )
            if value.contains_aggregate:
                raise FieldError("Aggregate functions are not allowed in this query")
        else:
            value = field.get_db_prep_save(value, connection=self.connection)
        return value 
Example 46
Project: LatinSounds_AppEnviaMail   Author: G3ek-aR   File: operations.py    (license) View Source Project 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        )
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass 
Example 47
Project: LatinSounds_AppEnviaMail   Author: G3ek-aR   File: subqueries.py    (license) View Source Project 6 votes vote down vote up
def add_update_values(self, values):
        """
        Convert a dictionary of field name to value mappings into an update
        query. This is the entry point for the public update() method on
        querysets.
        """
        values_seq = []
        for name, val in six.iteritems(values):
            field = self.get_meta().get_field(name)
            direct = not (field.auto_created and not field.concrete) or not field.concrete
            model = field.model._meta.concrete_model
            if not direct or (field.is_relation and field.many_to_many):
                raise FieldError(
                    'Cannot update model field %r (only non-relations and '
                    'foreign keys permitted).' % field
                )
            if model is not self.get_meta().model:
                self.add_related_update(model, field, val)
                continue
            values_seq.append((field, model, val))
        return self.add_update_fields(values_seq) 
Example 48
Project: LatinSounds_AppEnviaMail   Author: G3ek-aR   File: query.py    (license) View Source Project 6 votes vote down vote up
def solve_lookup_type(self, lookup):
        """
        Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
        """
        lookup_splitted = lookup.split(LOOKUP_SEP)
        if self._annotations:
            expression, expression_lookups = refs_expression(lookup_splitted, self.annotations)
            if expression:
                return expression_lookups, (), expression
        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
        field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
        if len(lookup_parts) == 0:
            lookup_parts = ['exact']
        elif len(lookup_parts) > 1:
            if not field_parts:
                raise FieldError(
                    'Invalid lookup "%s" for model %s".' %
                    (lookup, self.get_meta().model.__name__))
        return lookup_parts, field_parts, False 
Example 49
Project: LatinSounds_AppEnviaMail   Author: G3ek-aR   File: query.py    (license) View Source Project 6 votes vote down vote up
def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
        if not allow_joins and LOOKUP_SEP in name:
            raise FieldError("Joined field references are not permitted in this query")
        if name in self.annotations:
            if summarize:
                # Summarize currently means we are doing an aggregate() query
                # which is executed as a wrapped subquery if any of the
                # aggregate() elements reference an existing annotation. In
                # that case we need to return a Ref to the subquery's annotation.
                return Ref(name, self.annotation_select[name])
            else:
                return self.annotation_select[name]
        else:
            field_list = name.split(LOOKUP_SEP)
            field, sources, opts, join_list, path = self.setup_joins(
                field_list, self.get_meta(),
                self.get_initial_alias(), reuse)
            targets, _, join_list = self.trim_joins(sources, join_list, path)
            if len(targets) > 1:
                raise FieldError("Referencing multicolumn fields with F() objects "
                                 "isn't supported")
            if reuse is not None:
                reuse.update(join_list)
            col = targets[0].get_col(join_list[-1], sources[0])
            return col 
Example 50
Project: LatinSounds_AppEnviaMail   Author: G3ek-aR   File: compiler.py    (license) View Source Project 6 votes vote down vote up
def prepare_value(self, field, value):
        """
        Prepare a value to be used in a query by resolving it if it is an
        expression and otherwise calling the field's get_db_prep_save().
        """
        if hasattr(value, 'resolve_expression'):
            value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
            # Don't allow values containing Col expressions. They refer to
            # existing columns on a row, but in the case of insert the row
            # doesn't exist yet.
            if value.contains_column_references:
                raise ValueError(
                    'Failed to insert expression "%s" on %s. F() expressions '
                    'can only be used to update, not to insert.' % (value, field)
                )
            if value.contains_aggregate:
                raise FieldError("Aggregate functions are not allowed in this query")
        else:
            value = field.get_db_prep_save(value, connection=self.connection)
        return value