0

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

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.