model: Model class
    fields: List of 2-tuples of the form (field, value) in order of descending priority
961595
def resolve_model(model, fields):
    
    for (f, v) in fields:
        if v is not None:
            try:
                kwargs = {f: v}
                obj = model.objects.get(**kwargs)
                return obj
            except model.DoesNotExist:
                pass
            except model.MultipleObjectsReturned:
                pass
    raise model.DoesNotExist()
856058
def sanitize_order(model):
    
    to_order_dict = {}

    order_field_names = []
    for field in model._meta.fields:
        if isinstance(field, models.IntegerField):
            order_field_names.append(field.name)

    for field_name in order_field_names:
        to_order_dict[field_name] = list(model.objects.all().order_by(\
                field_name, '-timestamp'))

    updates = {}
    for field_name, object_list in to_order_dict.items():
        for i, obj in enumerate(object_list):
            position = i + 1
            if getattr(obj, field_name) != position:
                if obj in updates:
                    updates[obj][field_name] = position
                else:
                    updates[obj] = {field_name: position}

    for obj, fields in updates.items():
        for field, value in fields.items():
            setattr(obj, field, value)
        obj.save()
971059
def _do_multivalued_field_facets(self, results, field_facets):
        
        facet_dict = {}

        for field in field_facets:
            facet_list = {}
            if not self._multi_value_field(field):
                continue

            for result in results:
                field_value = getattr(result, field)
                for item in field_value:  # Facet each item in a MultiValueField
                    facet_list[item] = facet_list.get(item, 0) + 1

            facet_dict[field] = list(facet_list.items())
        return facet_dict
694925
def _sort_by_unique_fields(model, model_objs, unique_fields):
    
    unique_fields = [
        field for field in model._meta.fields
        if field.attname in unique_fields
    ]

    def sort_key(model_obj):
        return tuple(
            field.get_db_prep_save(getattr(model_obj, field.attname),
                                   connection)
            for field in unique_fields
        )
    return sorted(model_objs, key=sort_key)
581853
def model_to_list(model_class, filter_dict=None, order_by_list=None,
                  select_related_fields=None, q_filter=None,
                  values=None,
                  to_json_method='to_json'):
    
    return model_to_page_list(model_class, page_num=None,
                              filter_dict=filter_dict, order_by_list=order_by_list,
                              select_related_fields=select_related_fields,
                              q_filter=q_filter, values=values,
                              to_json_method=to_json_method)
721348
def _get_concrete_fields_with_model(self):
        
        return [
            (f, f.model if f.model != self.model else None)
            for f in self.model._meta.get_fields()
            if f.concrete
            and (
                not f.is_relation or f.one_to_one or (f.many_to_one and f.related_model)
            )
        ]
1038405
def _get_fields_for_model(model):
    
    fields = []
    for name in model._sa_class_manager:
        prop = getattr(model, name)
        if isinstance(prop.property, RelationshipProperty):
            for pk in prop.property.mapper.primary_key:
                fields.append('{0}.{1}'.format(name, pk.name))
        else:
            fields.append(name)
    return tuple(fields)
430306
def fields(self):
        ''''''
        key = self.id + ':fields'
        encoding = self.client.encoding
        return tuple(sorted((f.decode(encoding)
                             for f in self.client.smembers(key))))
143785
def order(self, last):
        ''''''
        desc = last.desc
        field = last.name
        nested = last.nested
        nested_args = []
        while nested:
            meta = nested.model._meta
            nested_args.extend((self.backend.basekey(meta), nested.name))
            last = nested
            nested = nested.nested
        method = 'ALPHA' if last.field.internal_type == 'text' else ''
        if field == last.model._meta.pkname():
            field = ''
        return {'field': field,
                'method': method,
                'desc': desc,
                'nested': nested_args}
692111
def _order(self, value, is_reverse=None):
        

        def _dict_parser(dict_doc):
            """ dict ordered by:
            valueType_N -> key_N -> value_N
            """
            result = list()
            for key in dict_doc:
                data = self._order(dict_doc[key])
                res = (data[0], key, data[1])
                result.append(res)
            return tuple(result)

        def _list_parser(list_doc):
            """list will iter members to compare
            """
            result = list()
            for member in list_doc:
                result.append(self._order(member))
            return result

        # (TODO) include more data type
        if value is None or not isinstance(value, (dict,
                                                   list,
                                                   basestring,
                                                   bool,
                                                   float,
                                                   int)):
            # not support/sortable value type
            value = (0, None)

        elif isinstance(value, bool):
            value = (5, value)

        elif isinstance(value, (int, float)):
            value = (1, value)

        elif isinstance(value, basestring):
            value = (2, value)

        elif isinstance(value, dict):
            value = (3, _dict_parser(value))

        elif isinstance(value, list):
            if len(value) == 0:
                # [] less then None
                value = [(-1, [])]
            else:
                value = _list_parser(value)

            if is_reverse is not None:
                # list will firstly compare with other doc by it's smallest
                # or largest member
                value = max(value) if is_reverse else min(value)
            else:
                # if the smallest or largest member is a list
                # then compaer with it's sub-member in list index order
                value = (4, tuple(value))

        return value
470609
def _get_related_fields(self, model):
        ""
        reverse_fk = self._get_all_related_objects(model)
        reverse_m2m = self._get_all_related_many_to_many_objects(model)

        fields = tuple(reverse_fk + reverse_m2m)
        names = tuple([x.get_accessor_name() for x in fields])

        return {
            ':related': dict(list(zip(names, fields))),
        }
197901
def prepare_fields_attribute(attribute_name, attributes, class_name):
        """"""
        attribute = attributes.get(attribute_name)
        if not attribute:
            attribute = tuple()
        elif isinstance(attribute, std_collections.Iterable):
            attribute = tuple(attribute)
        else:
            raise errors.Error('{0}.{1} is supposed to be a list of {2}, '
                               'instead {3} given', class_name, attribute_name,
                               fields.Field, attribute)
        return attribute
418101
def order_by(self, field, orientation='ASC'):
        
        if isinstance(field, list):
            self.raw_order_by.append(field)
        else:
            self.raw_order_by.append([field, orientation])

        return self
993730
def field2range(self, field, **kwargs):
        
        validators = [
            validator
            for validator in field.validators
            if (
                hasattr(validator, "min")
                and hasattr(validator, "max")
                and not hasattr(validator, "equal")
            )
        ]

        attributes = {}
        for validator in validators:
            if validator.min is not None:
                if hasattr(attributes, "minimum"):
                    attributes["minimum"] = max(attributes["minimum"], validator.min)
                else:
                    attributes["minimum"] = validator.min
            if validator.max is not None:
                if hasattr(attributes, "maximum"):
                    attributes["maximum"] = min(attributes["maximum"], validator.max)
                else:
                    attributes["maximum"] = validator.max
        return attributes
1086200
def get_ordering_for_column(self, column, direction):
        
        if direction == 0:
            return ()
        if column in self.orderings:
            ordering = self.orderings[column]
        else:
            field = self.get_field(column)
            if field is None:
                return ()
            ordering = column
        if not isinstance(ordering, (tuple, list)):
            ordering = [ordering]
        if direction == 1:
            return ordering
        return [lookup[1:] if lookup[0] == '-' else '-' + lookup
                for lookup in ordering]
883811
def _list_fields(self):
        
        opts = {'model': self.__proxy__, 'model_name': self.__name__}
        response = _turicreate.extensions._nearest_neighbors.list_fields(opts)

        return sorted(response.keys())
1160070
function parseField(field, fieldName, model) {
		// parse & check attributes and include
		parseIncludes(field, fieldName, model.name, model);

		// parse & check order
		parseOrders(field, fieldName, model);
	}