Reputation: 39
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.
Upvotes: 0
Views: 37
Reputation: 599480
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.
Upvotes: 1
Reputation: 2122
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
Upvotes: 0