Is there anyway to print complex tables embedded in strings in python? - python

I'm trying to print a confusion matrix, but I'm not sure if there is an easy way to print this kind of tables without write complex loops to concatenate the string. Right now, I just did it like this example. Is it there a different way.
t1 = "|" + " " \* 8 + "|" + " " \* 10 + "| Predicted |" + " " \*10 + "|\\n"
t2 = "|" + " " \* 8 + "|" + " " \* 10 + "| Positive |" + " Negative |\\n"
t3 = "| Actual |" + " Positive |" + " " \* (10 - len(str(TP))) + str(TP) + " |" + " " \* (9 - len(str(FN))) + str(FN) + " |\\n"
t4 = "|" + " " \* 8 + "|" + " Negative |" + " " \* (10 - len(str(FP))) + str(FP) + " |" + " " \* (9 - len(str(TN))) + str(TN) + " |\\n"
print(t1+t2+t3+t4)
| | | Predicted | |
| | | Positive | Negative |
| Actual | Positive | 1 | 2 |
| | Negative | 1 | 2 |
I am trying to find an easy way to print this kind of tables.

Related

Why will the value not replace when the function is called?

I’m attempting to make a game called nine men’s morris in python, and I can’t figure out
why the string won’t replace when conditions are satisfied the next time the
gameplay_board() function is called. anyone have any ideas?
I was expecting the value of a1 to be changed from ' ' to ○, but it doesn’t seem to work.
#ring 1
a1="1"
b1="2"
c1="3"
d1="4"
e1="5"
f1="6"
g1="7"
h1="8"
#ring 2
a2="1"
b2="2"
c2="3"
d2="4"
e2="5"
f2="6"
g2="7"
h2="8"
#ring 3
a3="1"
b3="2"
c3="3"
d3="4"
e3="5"
f3="6"
g3="7"
h3="8"
def example_board():
global a1, b1, c1, d1, e1, f1, g1, h1, a2, b2, c2, d2, e2, f2, g2, h2, a3, b3, c3, d3, e3, f3, g3, h3
print("\n" +
a1 + "----------" + b1 + "----------" + c1 + "\n" +
"| | |" + "<---Ring 1" + "\n" +
"| " + a2 + "-------" + b2 + "-------" + c2 + " |" + "\n" +
"| | | |<---Ring 2" + "\n" +
"| | " + a3 + "----" + b3 + "----" + c3 + " | |" + "\n" +
"| | | |<---Ring 3" + "\n" +
d1 + "--" + d2 + "--" + d3 + " " + e3 + "--" + e2 + "--" + e1 + "\n" +
"| | | | | |" + "\n" +
"| | " + f3 + "----" + g3 + "----" + h3 + " | |" + "\n" +
"| | | | |" + "\n" +
"| " + f2 + "-------" + g2 + "-------" + h2 + " |" + "\n" +
"| | |" + "\n" +
f1 + "----------" + g1 + "----------" + h1 + "\n" + "_______________________" + "\n")
a1=" "
b1=" "
c1=" "
d1=" "
e1=" "
f1=" "
g1=" "
h1=" "
a2=" "
b2=" "
c2=" "
d2=" "
e2=" "
f2=" "
g2=" "
h2=" "
a3=" "
b3=" "
c3=" "
d3=" "
e3=" "
f3=" "
g3=" "
h3=" "
example_board()
def gameplay_board():
print("\n" +
" " + "----------" + " " + "----------" + " " + "\n" +
"| | |" + "\n" +
"| " + " " + "-------" + " " + "-------" + " " + " |" + "\n" +
"| | | | |" + "\n" +
"| | " + " " + "----" + " " + "----" + " " + " | |" + "\n" +
"| | | | | |" + "\n" +
d1 + "--" + d2 + "--" + d3 + " " + e3 + "--" + e2 + "--" + e1 + "\n" +
"| | | | | |" + "\n" +
"| | " + f3 + "----" + g3 + "----" + h3 + " | |" + "\n" +
"| | | | |" + "\n" +
"| " + f2 + "-------" + g2 + "-------" + h2 + " |" + "\n" +
"| | |" + "\n" +
f1 + "----------" + g1 + "----------" + h1 + "\n" + "_______________________" + "\n")
#gameplay_board()
def update():
gameplay_board()
turn=1
bpp=0
wpp=0
def place_pieces():
ringchoice=int(input("Player 1, please select a ring to place your piece on. "))
if ringchoice==1: #and ringchoice=="one":
spotchoice=input("Player 1, please chose a spot to place your piece on. ")
if spotchoice==1:
a1="○"
gameplay_board()

I was creating a bot to snipe hypixel api discord bot but its creating a error by channel.send_message ,

done = default_timer() - START_TIME
if op:
winsound.Beep(500, 500) # emits a frequency 500hz, for 500ms
for result in results:
profit = result[1] - result[0][2]
print("/viewauction " + str(result[0][0]) + " | Item Name: " + str(result[0][1]) + " | Item price: {:,}".format(result[0][2]) + " | Profit : {:,}".format(profit) + " | Time to refresh AH: " + str(round(done, 2)))
print('\x1b[6;30;42m' + 'Sniping Auctions :)' + '\x1b[0m')
channel = client.get_channel(954629794224566302)
channel.send_message("/viewauction " + str(result[0][0]) + " | Item Name: " + str(result[0][1]) + " | Item price: {:,}".format(result[0][2]) + " | Profit : {:,}".format(profit) + " | Time to refresh AH: " + str(round(done, 2)))
This code is not very helpful and provide the error message.
btw channel.send_message() is replaced with channel.send()

Getting the subheaders in openpyxl

I'm currently using openpyxl to use an excel file that has mul-indices (2 Levels of headers) and i'm trying to do the operations depending on the subheaders a header has.
I have some exp. doing this in pandas but for this Project i have to use openpyxl which i barly made any use of before.
Only thing i could think off is the manual way:
iterating over the rows
saving the first row as header and 2nd row as subheader
do some cleaning.
manually save the headers with their subheaders in dics. then filleing in the values by iterating over all the cols
my code is as follows:
#reading the excel file
path = r'path to file'
wb = load_workbook(path) #loading the excel table
ws = wb.active #grab the active worksheet
#Setting the doc Header
for h in ws.iter_rows(max_row = 1, values_only = True): #getting the first row (Headers) in the table
header = list(h)
for sh in ws.iter_rows(min_row = 1 ,max_row = 2, values_only = True):
sub_header = list(sh)
#removing all of the none Values
header = list(filter(None, header))
sub_header = list(filter(None, sub_header))
print(header)
print(sub_header)
#creating a list of all the Columns in the excel file
col_list = []
for col in ws.iter_cols(min_row=3,min_col = 1): #Iteration over every single row starting from the third row since first two are the headers
col = [cell.value for cell in col] #Creating a list from each row
col = list(filter(None, col)) #removing the none values from each row
col_list.append(col) #creating a list of all rows (starting from the 3d one)
#print (col_list)
But i'm sure there must be a better way that i wasnt able to find in the docs or by checking this website.
Thanks in advance!
My goal in the end is to automate this part of my code by iterating over the header and use the subheaders of that head and their values each time
code:
#bulding the templates using yattag "yattag.org"
doc , tag , text = Doc().tagtext()
#building the tags of the xml file
with tag("Data"): #root tag
for row in row_list :
with tag("Row"):
with tag("Input"):
with tag(header[0].replace(' ','_').replace('\n','_')):
text("In " + dic[row[0]]+" the precentage of Students " + " regarding the " + header[0] + " the Precentage of Students with "+ sub_header[0] + " is "+ str(row[1]) + " whereas the " + sub_header[1] + " are " + str(row[2]) )
with tag("Row_Data"):
text(dic[row[0]] + " | " + header[0] + " | " + sub_header[0]+ " | " + str(row[1]) + " | " + sub_header[1] + " | " + str(row[2]))
with tag(header[1].replace(' ','_').replace('\n','_')):
text("In " + dic[row[0]]+" the precentage of Students " + " regarding the " + header[1] + " the Precentage of Students with "+ sub_header[2] + " is "+ str(row[3]) + " whereas the " + sub_header[3] + " are " + str(row[4]) )
with tag("Row_Data"):
text(dic[row[0]] + " | " + header[1] + " | " + sub_header[2]+ " | " + str(row[3]) + " | " + sub_header[3] + " | " + str(row[4]))
with tag(header[2].replace(' ','_').replace('\n','_')):
text("In " + dic[row[0]]+" the precentage of Students " + " regarding the " + header[2] + " the Precentage of Students with "+ sub_header[4] + " is "+ str(row[5]) + " whereas the " + sub_header[5] + " are " + str(row[6]) )
with tag("Row_Data"):
text(dic[row[0]] + " | " + header[2] + " | " + sub_header[4]+ " | " + str(row[5]) + " | " + sub_header[5] + " | " + str(row[6]))
with tag(header[3].replace(' ','_').replace('\n','_')):
text("In " + dic[row[0]]+" the precentage of Students " + " regarding the " + header[3] + " the Precentage of Students with "+ sub_header[6] + " is "+ str(row[7]) + " whereas the " + sub_header[7] + " are " + str(row[8]) +" and for " + sub_header[8] + str(row[9]) )
with tag("Row_Data"):
text(dic[row[0]] + " | " + header[3] + " | " + sub_header[6]+ " | " + str(row[7]) + " | " + sub_header[7] + " | " + str(row[8]) + " | " + sub_header[8] + " | " + str(row[9]))
with tag(header[4].replace(' ','_').replace('\n','_')):
text("In " + dic[row[0]]+" the precentage of Students " + " regarding the " + header[4] + " the Precentage of Students with "+ sub_header[9] + " is "+ str(row[10]) + " whereas the " + sub_header[10] + " are " + str(row[11]) )
with tag("Row_Data"):
text(dic[row[0]] + " | " + header[4] + " | " + sub_header[9]+ " | " + str(row[10]) + " | " + sub_header[10] + " | " + str(row[11]))
with tag(header[5].replace(' ','_').replace('\n','_')):
text("In " + dic[row[0]]+" the precentage of Students " + " regarding the " + header[5] + " the Precentage of Students with "+ sub_header[11] + " is "+ str(row[12]) + " whereas the " + sub_header[12] + " are " + str(row[13]) )
with tag("Row_Data"):
text(dic[row[0]] + " | " + header[5] + " | " + sub_header[11]+ " | " + str(row[12]) + " | " + sub_header[12] + " | " + str(row[13]))
with tag(header[6].replace(' ','_').replace('\n','_')):
text("In " + dic[row[0]]+" the precentage of Students " + " regarding the " + header[6] + " the Precentage of Students with "+ sub_header[13] + " is "+ str(row[14]) + " whereas the " + sub_header[14] + " are " + str(row[15]) )
with tag("Row_Data"):
text(dic[row[0]] + " | " + header[6] + " | " + sub_header[13]+ " | " + str(row[14]) + " | " + sub_header[14] + " | " + str(row[15]))
#print(doc.getvalue())
result = indent(
doc.getvalue(),
indentation=' ',
indent_text=True
)
#saving the xml file
with open("output.xml", "w") as f:
f.write(result)
Unless Pandas is completely off the table I think you might be able to do something pandas and openpyxl. The documentation mentions reading data from openpyxl into a pandas dataframe: Working with Pandas and Numpy.
Could you use:
data = ws.values
df = DataFrame(data[2:,:], index=data[0], columns=data[1])
There may be some filtering necessary with regards to the None values.

Python: Return variables from one function to the other without rerunning the first function

I'm new to programming and new to python. I have made some small projects (rock-paper-scissor and hangman) without major issues. In an attempt to challenge myself I'm trying to make a game of 4 in a row without an example to base it of. I have created multiple functions which represent a piece/step of the game.
One of the functions (get_player_input) takes care of the user input. I ask the user to select a column. I then check multiple things (is it a int from 1 till 7 and is the column not full?). If the input is valid, I return the variables column_select and free_places_column. The reason I return these variables is because I want to reuse this information to "place a piece" on the gameboard with the second function (place_piece)
This is where I get lost. I'm able to use these variables with use of: column_select, free_places_column = get_player_input() However this piece of code reruns the function get_player_input. Resulting in the user being asked twice in which column he want to put a piece.
My code thusfar:
# The game 4 in a row
# Define the game table with 6 rows and 7 columns
game_board = [[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "]]
# print the game board
def printboard():
print("|", game_board[0][0], "|", game_board[0][1], "|", game_board[0][2], "|", game_board[0][3], "|",
game_board[0][4], "|", game_board[0][5], "|", game_board[0][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[1][0], "|", game_board[1][1], "|", game_board[1][2], "|", game_board[1][3], "|",
game_board[1][4], "|", game_board[1][5], "|", game_board[1][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[2][0], "|", game_board[2][1], "|", game_board[2][2], "|", game_board[2][3], "|",
game_board[2][4], "|", game_board[2][5], "|", game_board[2][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[3][0], "|", game_board[3][1], "|", game_board[3][2], "|", game_board[3][3], "|",
game_board[3][4], "|", game_board[3][5], "|", game_board[3][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[4][0], "|", game_board[4][1], "|", game_board[4][2], "|", game_board[4][3], "|",
game_board[4][4], "|", game_board[4][5], "|", game_board[4][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[5][0], "|", game_board[5][1], "|", game_board[5][2], "|", game_board[5][3], "|",
game_board[5][4], "|", game_board[5][5], "|", game_board[5][6], "|")
print("- - + - + - + - + - + - + - -")
print(" 1 2 3 4 5 6 7")
print()
def get_player_input():
# set varaibles
free_places_column = 0
received_valid_input = False
# Validate if player input is int and anywhere from 1 to 7. if not ask again
while received_valid_input == False:
try:
column_select = int(input("Which column (1-7) do you want to drop the piece: "))
if 0 < column_select < 8:
for i in range(0, 6):
if game_board[i][column_select - 1] == " ":
free_places_column = free_places_column + 1
if free_places_column == 0:
print("Column is full. please select an other column")
else:
received_valid_input = True
else:
print('Please provide a number between 1 and 7')
except ValueError:
print('Wrong input. Please enter a number between 1 and 7')
return column_select, free_places_column
def place_piece(player):
column_select, free_places_column = get_player_input()
print("Going to place a piece in column", column_select, "and row", free_places_column)
if player == "A":
game_board[free_places_column - 1][column_select - 1] = "X"
else:
game_board[free_places_column - 1][column_select - 1] = "O"
while True:
printboard()
get_player_input()
place_piece("A")
When I run this code this is the result:
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
1 2 3 4 5 6 7
Which column (1-7) do you want to drop the piece: 1
Which column (1-7) do you want to drop the piece: 1
Going to place a piece in column 1 and row 6
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| X | | | | | | |
- - + - + - + - + - + - + - -
1 2 3 4 5 6 7
I have searched the internet and watched YouTube tutorials on retuning variables from one function to the other but I have not yet found how to deal with this. I found some this which could solve my issues but none of them seem the way to go for now:
Make my variables global --> found many, many people telling other people not to do this
Start using classes --> Still a difficult concept to grasp for me. Also kind of want to solve this without completely moving away from the choices thusfar
Ditch the functions and make 1 big piece of code --> Trying to learn to use functions
I also wrote a small piece of code to remove some of the complexity. Hopefully making it easier to understand for myself:
def function1():
a = 10
b = 20
print("We are in function 1")
return a, b
def function2():
a, b = function1()
print(a, b)
print("We are in function 2")
function1()
function2()
Result:
We are in function 1
We are in function 1
10 20
We are in function 2
Can anybody point me in the right direction?
Best regards
# The game 4 in a row
# Define the game table with 6 rows and 7 columns
game_board = [[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "]]
# print the game board
def printboard():
print("|", game_board[0][0], "|", game_board[0][1], "|", game_board[0][2], "|", game_board[0][3], "|",
game_board[0][4], "|", game_board[0][5], "|", game_board[0][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[1][0], "|", game_board[1][1], "|", game_board[1][2], "|", game_board[1][3], "|",
game_board[1][4], "|", game_board[1][5], "|", game_board[1][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[2][0], "|", game_board[2][1], "|", game_board[2][2], "|", game_board[2][3], "|",
game_board[2][4], "|", game_board[2][5], "|", game_board[2][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[3][0], "|", game_board[3][1], "|", game_board[3][2], "|", game_board[3][3], "|",
game_board[3][4], "|", game_board[3][5], "|", game_board[3][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[4][0], "|", game_board[4][1], "|", game_board[4][2], "|", game_board[4][3], "|",
game_board[4][4], "|", game_board[4][5], "|", game_board[4][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[5][0], "|", game_board[5][1], "|", game_board[5][2], "|", game_board[5][3], "|",
game_board[5][4], "|", game_board[5][5], "|", game_board[5][6], "|")
print("- - + - + - + - + - + - + - -")
print(" 1 2 3 4 5 6 7")
print()
def get_player_input():
# set varaibles
free_places_column = 0
received_valid_input = False
# Validate if player input is int and anywhere from 1 to 7. if not ask again
while received_valid_input == False:
try:
column_select = int(input("Which column (1-7) do you want to drop the piece: "))
if 0 < column_select < 8:
for i in range(0, 6):
if game_board[i][column_select - 1] == " ":
free_places_column = free_places_column + 1
if free_places_column == 0:
print("Column is full. please select an other column")
else:
received_valid_input = True
else:
print('Please provide a number between 1 and 7')
except ValueError:
print('Wrong input. Please enter a number between 1 and 7')
return column_select, free_places_column
def place_piece(player):
column_select, free_places_column = get_player_input()
print("Going to place a piece in column", column_select, "and row", free_places_column)
if player == "A":
game_board[free_places_column - 1][column_select - 1] = "X"
else:
game_board[free_places_column - 1][column_select - 1] = "O"
while True:
printboard()
place_piece("A")
I just removed one line in your while True loop.
As you call get_player_input() in place_piece(player) function, there is noneed to call it twice.
You want both functions to be executed in a given order, but since the get_player_input() is embedded in the code of place_piece(player), you just need to execute place_piece(player).
To use your simple example:
def function1():
a = 10
b = 20
print("We are in function 1")
return a, b
def function2():
a, b = function1()
print(a, b)
print("We are in function 2")
If you call only function2(), the ouput is:
We are in function 1
10 20
We are in function 2
If you call only function1(), the output is:
We are in function 1
If you call function1() and then function2(), the output is:
We are in function 1
We are in function 1
10 20
We are in function 2
And function2() and then function1():
We are in function 1
10 20
We are in function 2
We are in function 1
To get what you want by calling two functions in your code, you need:
def function1():
a = 10
b = 20
print("We are in function 1")
return a, b
def function2(a,b):
print(a, b)
print("We are in function 2")
a, b = function1()
function2(a,b)
And you get:
We are in function 1
10 20
We are in function 2
With your full code:
# The game 4 in a row
# Define the game table with 6 rows and 7 columns
game_board = [[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "]]
# print the game board
def printboard():
print("|", game_board[0][0], "|", game_board[0][1], "|", game_board[0][2], "|", game_board[0][3], "|",
game_board[0][4], "|", game_board[0][5], "|", game_board[0][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[1][0], "|", game_board[1][1], "|", game_board[1][2], "|", game_board[1][3], "|",
game_board[1][4], "|", game_board[1][5], "|", game_board[1][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[2][0], "|", game_board[2][1], "|", game_board[2][2], "|", game_board[2][3], "|",
game_board[2][4], "|", game_board[2][5], "|", game_board[2][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[3][0], "|", game_board[3][1], "|", game_board[3][2], "|", game_board[3][3], "|",
game_board[3][4], "|", game_board[3][5], "|", game_board[3][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[4][0], "|", game_board[4][1], "|", game_board[4][2], "|", game_board[4][3], "|",
game_board[4][4], "|", game_board[4][5], "|", game_board[4][6], "|")
print("- - + - + - + - + - + - + - -")
print("|", game_board[5][0], "|", game_board[5][1], "|", game_board[5][2], "|", game_board[5][3], "|",
game_board[5][4], "|", game_board[5][5], "|", game_board[5][6], "|")
print("- - + - + - + - + - + - + - -")
print(" 1 2 3 4 5 6 7")
print()
def get_player_input():
# set varaibles
free_places_column = 0
received_valid_input = False
# Validate if player input is int and anywhere from 1 to 7. if not ask again
while received_valid_input == False:
try:
column_select = int(input("Which column (1-7) do you want to drop the piece: "))
if 0 < column_select < 8:
for i in range(0, 6):
if game_board[i][column_select - 1] == " ":
free_places_column = free_places_column + 1
if free_places_column == 0:
print("Column is full. please select an other column")
else:
received_valid_input = True
else:
print('Please provide a number between 1 and 7')
except ValueError:
print('Wrong input. Please enter a number between 1 and 7')
return column_select, free_places_column
def place_piece(player,column_select,free_places_column):
print("Going to place a piece in column", column_select, "and row", free_places_column)
if player == "A":
game_board[free_places_column - 1][column_select - 1] = "X"
else:
game_board[free_places_column - 1][column_select - 1] = "O"
while True:
printboard()
column_select, free_places_column = get_player_input()
place_piece("A",column_select, free_places_column)
Output:
Which column (1-7) do you want to drop the piece: 2
Going to place a piece in column 2 and row 6
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | X | | | | |
- - + - + - + - + - + - + - -
| X | X | X | | | | |
- - + - + - + - + - + - + - -
1 2 3 4 5 6 7
Which column (1-7) do you want to drop the piece: 3
Going to place a piece in column 3 and row 4
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | | | | | |
- - + - + - + - + - + - + - -
| | | X | | | | |
- - + - + - + - + - + - + - -
| | | X | | | | |
- - + - + - + - + - + - + - -
| X | X | X | | | | |
- - + - + - + - + - + - + - -
1 2 3 4 5 6 7
Which column (1-7) do you want to drop the piece:

Get field name from an object retrieved by orm query

I have a small Django app, and when I query my DB with django orm I get my objects list.
What I want is the name of the db column where the query has matched.
Is possible?
Thanks in advance!
results = Verbs.objects.filter(
Q(fps__icontains = " " + word_name + " ") | Q(fps__endswith = " " + word_name) | Q(fps__startswith = word_name + " ") |
Q(sps__icontains = " " + word_name + " ") | Q(sps__endswith = " " + word_name) | Q(sps__startswith = word_name + " ") |
Q(tps__icontains = " " + word_name + " ") | Q(tps__endswith = " " + word_name) | Q(tps__startswith = word_name + " ") |
Q(fpp__icontains = " " + word_name + " ") | Q(fpp__endswith = " " + word_name) | Q(fpp__startswith = word_name + " ") |
Q(spp__icontains = " " + word_name + " ") | Q(spp__endswith = " " + word_name) | Q(spp__startswith = word_name + " ") |
Q(tpp__icontains = " " + word_name + " ") | Q(tpp__endswith = " " + word_name) | Q(tpp__startswith = word_name + " ")
).all()
What I want is the name of field where the query as matched. For example: fps or fpp ...
I think this is what you want--for each returned row it will print the matched fields, indented:
fields = ('fps', 'sps', 'tps', 'fpp', 'spp', 'tpp')
for r in results.values():
print 'Row with id=%s:' % r['id']
for f in fields:
if word_name in str(r[f]):
print ' Field %s matches' % f
Edited to account for non-string values and to look only at the desired fields.

Categories

Resources