def convert_lookup(model, joins, lookup):
    """
    Given a model, a graph of joins, and a lookup, return a tuple containing
    a normalized lookup:

    (model actually being queried, updated graph of joins, normalized lookup)
    """
    operations = model._meta.database.adapter.operations

    pieces = lookup.split('__')
    operation = None

    query_model = model

    if len(pieces) > 1:
        if pieces[-1] in operations:
            operation = pieces.pop()

        lookup = pieces.pop()

        # we have some joins
        if len(pieces):
            for piece in pieces:
                # piece is something like 'blog' or 'entry_set'
                joined_model = None
                for field in query_model._meta.get_fields():
                    if not isinstance(field, ForeignKeyField):
                        continue

                    if piece in (field.name, field.db_column, field.related_name):
                        joined_model = field.to

                if not joined_model:
                    try:
                        joined_model = query_model._meta.reverse_relations[piece]
                    except KeyError:
                        raise ValueError('Unknown relation: "%s" of "%s"' % (
                            piece,
                            query_model,
                        ))

                joins.setdefault(query_model, set())
                joins[query_model].add(joined_model)
                query_model = joined_model

    if operation:
        lookup = '%s__%s' % (lookup, operation)

    return query_model, joins, lookup
dataset/ETHPy150Open kuri65536/python-for-android/sl4atools/fullscreenwrapper2/examples/calcount2_example/peewee.py/convert_lookup/original