def _pk_trace(self, value, prep_func, lookup_type, **kwargs):
        # Value may be a primary key, or an object held in a relation.
        # If it is an object, then we need to get the primary key value for
        # that object. In certain conditions (especially one-to-one relations),
        # the primary key may itself be an object - so we need to keep drilling
        # down until we hit a value that can be used for a comparison.
        v = value

        # In the case of an FK to 'self', this check allows to_field to be used
        # for both forwards and reverse lookups across the FK. (For normal FKs,
        # it's only relevant for forward lookups).
        if isinstance(v, self.rel.to):
            field_name = getattr(self.rel, "field_name", None)
        else:
            field_name = None
        try:
            while True:
                if field_name is None:
                    field_name = v._meta.pk.name
                v = getattr(v, field_name)
                field_name = None
        except __HOLE__:
            pass
        except exceptions.ObjectDoesNotExist:
            v = None

        field = self
        while field.rel:
            if hasattr(field.rel, 'field_name'):
                field = field.rel.to._meta.get_field(field.rel.field_name)
            else:
                field = field.rel.to._meta.pk

        if lookup_type in ('range', 'in'):
            v = [v]
        v = getattr(field, prep_func)(lookup_type, v, **kwargs)
        if isinstance(v, list):
            v = v[0]
        return v
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/models/fields/related.py/RelatedField._pk_trace