'Resolve the references of this item (=look up all foreign
keys from other items of the same job). If a foreign key
is not yet available, it will be scheduled for later update.'

def _resolve_references(self):

    table = self.table
    if (not table):
        return
    db = current.db
    items = self.job.items
    for reference in self.references:
        entry = reference.entry
        if (not entry):
            continue
        field = reference.field
        if isinstance(field, (list, tuple)):
            (pkey, fkey) = field
        else:
            (pkey, fkey) = ('id', field)
        (ktablename, key, multiple) = s3_get_foreign_key(table[fkey])
        if (not ktablename):
            continue
        if entry.tablename:
            ktablename = entry.tablename
        try:
            ktable = current.s3db[ktablename]
        except:
            continue
        item = None
        fk = entry.id
        if entry.item_id:
            item = items[entry.item_id]
            if item:
                if (item.original and item.original.get('deleted') and (not item.committed)):
                    fk = None
                else:
                    fk = item.id
        if (fk and (pkey != 'id')):
            row = db((ktable._id == fk)).select(ktable[pkey], limitby=(0, 1)).first()
            if (not row):
                fk = None
                continue
            else:
                fk = row[pkey]
        if fk:
            if multiple:
                val = self.data.get(fkey, [])
                if (fk not in val):
                    val.append(fk)
                self.data[fkey] = val
            else:
                self.data[fkey] = fk
        else:
            if ((fkey in self.data) and (not multiple)):
                del self.data[fkey]
            if item:
                item.update.append(dict(item=self, field=fkey))
