I am trying to find out if a value is present in a column in a MySQL table from my django application. This is what I have done:
cursor = connection.cursor()
cursor.execute('SELECT COUNT(*) FROM model_combination_bank WHERE combination = %s AND validity = 1', [combination])
result = cursor.fetchall
if result != 1:
self.respond('Sorry. The entry code you entered is not valid. Please try again with a valid code.')
return()
I know for sure that there is a 1 row in the table that matches the SELECT STATEMENT but the self.respond function runs. Can somebody kindly tell me whats wrong with my code.
2 Answers 2
You didn't call the method:
result = cursor.fetchall()
However you shouldn't really be using raw SQL here. Use the model layer:
result = ModelCombinationBank.objects.filter(validity=1, combination=combination).count()
assuming your model is called ModelCombinationBank. And if all you need to is to check that the combination exists, use exists() instead of count(), since that is a cheaper query.
Comments
Another way to see if a value exists and do something if it does:
try:
obj = ModelCombinationBank.objects.get(validity=1, combination=combination)
# do something with obj
except ModelCombinationBank.DoesNotExist:
# do something if not found