Follows the queryset-style query path of ``orm_path`` starting from ``model`` class.  If the
    path ends up referring to a bad field name, ``django.db.models.fields.FieldDoesNotExist`` will
    be raised.
437411
def resolve_orm_path(model, orm_path):
    

    bits = orm_path.split('__')
    endpoint_model = reduce(get_model_at_related_field, [model] + bits[:-1])
    if bits[-1] == 'pk':
        field = endpoint_model._meta.pk
    else:
        field = endpoint_model._meta.get_field(bits[-1])
    return field
466977
def _get_model_fields(self, model, prefix=_field_prefix):
        
        fields = list()
        for field_name, field in model()._ordered_fields:
            # Filter the default fields
            if field_name not in getattr(model, '_DEFAULT_BASE_FIELDS', []):
                type_name = utils.to_camel(field.solr_type)
                required = self._marker_true if field.required is True else self._marker_false
                fields.append((prefix, field_name, type_name, required))

        return fields
21810
def get_field(cls, model, opts, label, field):
    

    trans_model = model._meta.translation_model
    try:
        (f, lang_id) = trans_model._meta.translated_fields[field]
        return f
    except KeyError:
        # fall back to the old way -- see if model contains the field
        # directly
        pass

    try:
        return opts.get_field(field)
    except models.FieldDoesNotExist:
        raise ImproperlyConfigured("'%s.%s' refers to field '%s' that is " \
            "missing from model '%s'." \
            % (cls.__name__, label, field, model.__name__))
830538
def ko(queryset, field_names=None):
    

    try:
        koDataString = ko_data(queryset, field_names)
        koModelString = ko_model(queryset[0].__class__.__name__, field_names, data=True)
        koBindingsString = ko_bindings(queryset[0])

        koString = koDataString + '\n' + koModelString + '\n' + koBindingsString

        return koString
    except Exception as e:
        logger.error(e)
        return ''
588838
def get_filterset_kwargs(self, request, queryset, view):
        
        filter_keys = []
        # rewrite filter[field] query params to make DjangoFilterBackend work.
        data = request.query_params.copy()
        for qp, val in request.query_params.items():
            m = self.filter_regex.match(qp)
            if m and (not m.groupdict()['assoc'] or
                      m.groupdict()['ldelim'] != '[' or m.groupdict()['rdelim'] != ']'):
                raise ValidationError("invalid query parameter: {}".format(qp))
            if m and qp != self.search_param:
                if not val:
                    raise ValidationError("missing {} test value".format(qp))
                # convert jsonapi relationship path to Django ORM's __ notation
                key = m.groupdict()['assoc'].replace('.', '__')
                # undo JSON_API_FORMAT_FIELD_NAMES conversion:
                key = format_value(key, 'underscore')
                data[key] = val
                filter_keys.append(key)
                del data[qp]
        return {
            'data': data,
            'queryset': queryset,
            'request': request,
            'filter_keys': filter_keys,
        }
1372705
def user_order_by(self, field):
    
    # Get ordering model.
    model_label = order.utils.resolve_labels('.'.join(\
            [self.model._meta.app_label, self.model._meta.object_name]))
    orderitem_set = getattr(self.model, \
            order.utils.resolve_order_item_related_set_name(model_label))
    order_model = orderitem_set.related.model

    # Resolve ordering model table name.
    db_table = order_model._meta.db_table

    # Add ordering field as extra queryset fields.
    pk_name = self.model._meta.pk.attname

    # If we have a descending query remove '-' from field name when quering.
    sanitized_field = field.lstrip('-')

    extra_select = {
        sanitized_field: '(SELECT %s from %s WHERE item_id=%s.%s)' % \
                (sanitized_field, db_table, self.model._meta.db_table, pk_name)
    }

    # Use original field name when ordering to allow for descending.
    return self.extra(select=extra_select).all().order_by(field)
290659
def get_path_fields(cls, base=[]):
    
    pfs = []
    for pf in cls.TutelaryMeta.path_fields:
        if pf == 'pk':
            pfs.append(base + ['pk'])
        else:
            f = cls._meta.get_field(pf)
            if isinstance(f, models.ForeignKey):
                pfs += get_path_fields(f.target_field.model, base=base + [pf])
            else:
                pfs.append(base + [f.name])
    return pfs
1256856
def build_q(fields_dict, params_dict, request=None):
    
    # Building search query
    # queries generated by different search_fields are ANDed
    # if a search field is defined for more than one field, are put together with OR
    and_query = Q()

    for fieldname in fields_dict:
        search_field = fields_dict[fieldname]
        if fieldname in params_dict and params_dict[fieldname] != '' and params_dict[fieldname] != []:
            or_query = None

            if type(search_field) == type(list()):
                field_list = search_field
                search_operator = "__icontains"
                fixed_filters = None
                multiple_values = False
                custom_query_method = None
                value_mapper = None

            else: # dictionary of field definitions
                if search_field.get('ignore', False):
                    continue

                field_list = search_field['fields']
                search_operator = search_field.get('operator', None)
                fixed_filters = search_field.get('fixed_filters', None)
                multiple_values = search_field.get('multiple', False)
                custom_query_method =  search_field.get('custom_query', None)
                value_mapper =  search_field.get('value_mapper', None)

            for model_field in field_list:

                if multiple_values:
                    if hasattr(params_dict, "getlist"):
                        request_field_value = params_dict.getlist(fieldname)
                    elif type(params_dict[fieldname]) == list:
                        request_field_value = params_dict[fieldname]
                    else:
                        request_field_value = [params_dict[fieldname]]
                    if value_mapper:
                        request_field_value = [value_mapper(value) for value in request_field_value]
                else:
                    request_field_value = params_dict[fieldname] if not value_mapper else value_mapper(params_dict[fieldname])

                if not custom_query_method:
                    fieldname_key = model_field + search_operator
                    filter_dict = { fieldname_key : request_field_value}
                    if not or_query:
                        or_query = Q(**filter_dict)
                    else:
                        or_query = or_query | Q(**filter_dict)
                else:
                    #TODO: this is a hack for using request data in custom_query
                    #it would be better to pass ALSO the request to custom_query_method
                    if not request:
                        cf = custom_query_method(model_field, request_field_value, params_dict)
                    else:
                        cf = custom_query_method(model_field, request_field_value, request)

                    if not or_query:
                        or_query = cf
                    else:
                        or_query = or_query | cf

            #fixed_filters
            fixed_filters_q = Q()
            #fixed_filters must return a Q object or None
            if fixed_filters:
                if callable(fixed_filters):
                    fixed_filters_q = fixed_filters(params_dict)
                elif type(fixed_filters) is dict:
                    fixed_filters_q = Q(**fixed_filters)

            and_query = and_query & or_query
            and_query = and_query & fixed_filters_q


    return and_query
1196478
def get_field_link(context, field, obj=None):
    
    view = context['view']
    return view.lookup_field_link(context, field, obj)
1118047
def _replace_path(self, path):
        
        if path in self._field_to_key:
            return self._field_to_key[path]
        next_key = "#f%d" % self._next_field
        self._next_field += 1
        self._field_to_key[path] = next_key
        self._fields[next_key] = path
        return next_key
1106300
def ordering_url(self, field_name):
        
        path = self.request.path
        direction = ""
        query_params = self.request.GET.copy()
        ordering = self.request.GET.get("order", "").split(",")
        field = self._get_ordering_field_lookup(field_name)
        if not ordering:
            ordering = self.get_default_ordering()
        merged_ordering = list(ordering)  # copy the list

        for ordering_field in self.get_ordering_fields_lookups():
            if (ordering_field.lstrip("-") not in ordering) and (
                ("-" + ordering_field.lstrip("-")) not in ordering
            ):
                merged_ordering.append(ordering_field)

        new_ordering = []
        for item in merged_ordering:
            if item.lstrip("-") == field.lstrip("-"):
                if (item[0] == "-") or not (item in ordering):
                    if item in ordering:
                        direction = "desc"
                    new_ordering.insert(0, item.lstrip("-"))
                else:
                    direction = "asc"
                    new_ordering.insert(0, "-" + item)

        query_params["order"] = ",".join(new_ordering)

        return (path + "?" + query_params.urlencode(safe=","), direction)
318210
def build_standard_field(self, field_name, model_field):
        
        kwargs = {}

        if model_field.null or model_field.blank:
            kwargs['required'] = False

            if model_field.null:
                kwargs['allow_null'] = True
            if model_field.blank and (issubclass(model_field.__class__, models.CharField) or
                                      (issubclass(model_field.__class__, models.TextField))):
                kwargs['allow_blank'] = True

        if isinstance(model_field, models.AutoField) or not model_field.editable:
            kwargs['read_only'] = True

        if model_field.has_default():
            kwargs['default'] = model_field.get_default()

        if issubclass(model_field.__class__, models.TextField):
            kwargs['style'] = {'base_template': 'textarea.html'}

        if model_field.verbose_name is not None:
            kwargs['label'] = model_field.verbose_name

        if model_field.help_text is not None:
            kwargs['help_text'] = model_field.help_text

        # TODO: TypedChoiceField?
        if model_field.flatchoices:  # This ModelField contains choices
            kwargs['choices'] = model_field.flatchoices
            if model_field.null:
                kwargs['empty'] = None
            return (ChoiceField, kwargs)

        # put this below the ChoiceField because min_value isn't a valid initializer
        if issubclass(model_field.__class__, models.PositiveIntegerField) or\
                issubclass(model_field.__class__, models.PositiveSmallIntegerField):
            kwargs['min_value'] = 0

        attribute_dict = {
            models.CharField: ['max_length'],
            models.CommaSeparatedIntegerField: ['max_length'],
            models.DecimalField: ['max_digits', 'decimal_places'],
            models.EmailField: ['max_length'],
            models.FileField: ['max_length'],
            models.ImageField: ['max_length'],
            models.SlugField: ['max_length'],
            models.URLField: ['max_length'],
        }

        # === django-rest-framework-hstore specific ====
        # if available, use __basefield__ attribute instead of __class__
        # this will cause DRF to pick the correct DRF-field
        key = getattr(model_field, '__basefield__', model_field.__class__)

        if key in attribute_dict:
            attributes = attribute_dict[key]
            for attribute in attributes:
                kwargs.update({attribute: getattr(model_field, attribute)})

        if model_field.__class__ == DictionaryField and model_field.schema:
            kwargs['schema'] = True

        try:
            return (self.serializer_field_mapping[key], kwargs)
        except KeyError:
            pass

        try:
            return (self.serializer_field_mapping[model_field.__class__.__name__], kwargs)
        except KeyError:
            # return ModelField(model_field=model_field, **kwargs)
            return super(HStoreSerializer, self).build_standard_field(field_name, model_field)
728756
def _validate_field(param, fields):
    

    if '/' not in param.field and param.field not in fields:
        raise InvalidQueryParams(**{
            'detail': 'The filter query param of "%s" is not possible. The '
                      'resource requested does not have a "%s" field. Please '
                      'modify your request & retry.' % (param, param.field),
            'links': LINK,
            'parameter': PARAM,
        })
446177
def get_instance_field(self, field_name):
        
        if not self.has_field(field_name):
            raise AttributeError('"%s" is not a field for the model "%s"' %
                                 (field_name, self.__class__.__name__))

        field = getattr(self, field_name)

        return field
964609
def match_field(field_class):
    
    for cls in field_class.mro():
        if cls in list(LOOKUP_TABLE.keys()):
            return cls
    # could not match the field class
    raise Exception('{0} None Found '.format(field_class))
872614
async def walk_query(obj, object_resolver, connection_resolver, errors, current_user=None, __naut_name=None, obey_auth=True, **filters):
    
    # if the object has no selection set
    if not hasattr(obj, 'selection_set'):
        # yell loudly
        raise ValueError("Can only resolve objects, not primitive types")

    # the name of the node
    node_name = __naut_name or obj.name.value if obj.name else obj.operation

    # the selected fields
    selection_set = obj.selection_set.selections

    def _build_arg_tree(arg):
        """
            This function recursively builds the arguments for lists and single values
        """
        # TODO: what about object arguments??

        # if there is a single value
        if hasattr(arg, 'value'):
            # assign the value to the filter
            return arg.value
        # otherwise if there are multiple values for the argument
        elif hasattr(arg, 'values'):
            return [_build_arg_tree(node) for node in arg.values]

    # for each argument on this node
    for arg in obj.arguments:
        # add it to the query filters
        filters[arg.name.value] = _build_arg_tree(arg.value)

    # the fields we have to ask for
    fields = [field for field in selection_set if not field.selection_set]
    # the links between objects
    connections = [field for field in selection_set if field.selection_set]

    try:
        # resolve the model with the given fields
        models = await object_resolver(node_name, [field.name.value for field in fields], current_user=current_user, obey_auth=obey_auth, **filters)
    # if something went wrong resolving the object
    except Exception as e:
        # add the error as a string
        errors.append(e.__str__())
        # stop here
        return None

    # add connections to each matching model
    for model in models:
        # if is an id for the model
        if 'pk' in model:
            # for each connection
            for connection in connections:
                # the name of the connection
                connection_name = connection.name.value
                # the target of the connection
                node = {
                    'name': node_name,
                    'pk': model['pk']
                }

                try:
                    # go through the connection
                    connected_ids, next_target = await connection_resolver(
                        connection_name,
                        node,
                    )

                    # if there are connections
                    if connected_ids:
                        # add the id filter to the list
                        filters['pk_in'] = connected_ids

                        # add the connection field
                        value = await walk_query(
                            connection,
                            object_resolver,
                            connection_resolver,
                            errors,
                            current_user=current_user,
                            obey_auth=obey_auth,
                            __naut_name=next_target,
                            **filters
                        )
                    # there were no connections
                    else:
                        value = []
                # if something went wrong
                except Exception as e:
                    # add the error as a string
                    errors.append(e.__str__())
                    # stop here
                    value = None

                # set the connection to the appropriate value
                model[connection_name] = value

    # return the list of matching models
    return models
224818
def get_queryset(self):
        
        queryset = super(NestedViewSetMixin, self).get_queryset()
        if hasattr(self.serializer_class, 'parent_lookup_kwargs'):
            orm_filters = {}
            for query_param, field_name in self.serializer_class.parent_lookup_kwargs.items():
                orm_filters[field_name] = self.kwargs[query_param]
            return queryset.filter(**orm_filters)
        return queryset