You here perform two queries: an EXISTS and a fetch. You can merge it into one:
discount_code_get = request.GET.get('discount')
discount_code= Discount.objects.filter(code=discount_code_get).first()
if discount_code is not None:
return discount_code.value
This works since .first() returns None if it can not find such database row.
Or even more efficient (given value is non-NULLable):
# In case value is non-NULLable
discount_code_get = request.GET.get('discount')
discount_value = Discount.objects.values_list(
'value', flat=True
).filter(code=discount_code_get).first()
if discount_value is not None:
return discount_value
In case the code is a unique field, it is more idiomatic to use a try-except here:
# in case code is unique
discount_code_get = request.GET.get('discount')
try:
discount_value = Discount.objects.values_list(
'value', flat=True
).get(code=discount_code_get)
except Discount.DoesNotExist:
pass
else:
print(discount_value)
Using .values_list(..) will reduce the number of columns that are fetched (and deserialized). Although that is typically not a huge boost, it can be significant if the number of columns is large, or the data stored in it is large, since then we save on deserializing attributes, that are never used later in the process.