云表关联外键时二次调用add_foreign_key函数报'bool'不可调用错误
Hey, let's break down why you're hitting that 'bool' object is not callable error when adding the foreign key for your child table, and how to fix it.
The Root Cause: Variable Name Shadowing
The problem comes down to a simple naming conflict in your main table code. Look at this line:
add_foreign_key = add_foreign_key(conn, cursor, 'SURVEYS', survey_new_title, 'SURVEY_ID', 'SURVEY_ID')
You’re using the exact same name for the variable storing the function’s return value as the function itself. After running this line, add_foreign_key is no longer a reference to your add_foreign_key() function—it’s now a boolean (True or False) from the function’s return.
When your child table code tries to call add_foreign_key(...), it’s trying to invoke that boolean value instead of the actual function. Booleans can’t be called like functions, hence the error.
Fix: Rename the Variable to Avoid Overwriting the Function
All you need to do is change the variable name in your main table code to something unique. For example:
add_dataframe = add_dataframe_as_table(conn, cursor, data, survey_new_title) if add_dataframe: # Simplified from if(add_dataframe==True) # Use a distinct variable name instead of reusing the function name fk_add_success = add_foreign_key(conn, cursor, 'SURVEYS', survey_new_title, 'SURVEY_ID', 'SURVEY_ID') # Add primary key for main table pk_add_success = add_primary_key_for_main_survey(conn, cursor, survey_new_title, '_INDEX')
Now add_foreign_key still points to your original function when you call it in the child table code, so it’ll run without issues.
Bonus: Fix a Syntax Issue in Your SQL Queries
I spotted a minor syntax bug in both your add_foreign_key and add_primary_key_for_main_survey functions. The .format() method is on a new line, which will throw a syntax error. Fix it by attaching .format() to the string, or using parentheses for clean line breaks:
In add_foreign_key:
# Fixed query formatting query = """ALTER TABLE {0} ADD FOREIGN KEY ({1}) REFERENCES {2}({3})""".format( child_table.replace('\'', '\'\''), child_table_key_name, reference_table_name, reference_table_key_name )
Apply the same fix to the query line in add_primary_key_for_main_survey too.
Wrap-Up
This is a classic case of variable name shadowing—you accidentally overwrote your function reference with a boolean value. Renaming the variable will resolve the "not callable" error right away. And fixing that SQL formatting issue will prevent another unexpected error once you get past this one.
内容的提问来源于stack exchange,提问作者alim1990

