Amit Pal
Amit Pal

Reputation: 11062

How to prevent code from showing an error after getting the value of model instance is NULL in Django?

I am writing my views.py, in which i need to get the model instance by following code:

model_instance = AlertCount.objects.get(user=request.user.username)

But at the first time after running python manage.py syncdb. The field of table is initially empty. So it shows this error

DoesNotExist: AlertCount matching query does not exist

It should be obvious. But according to my views.py method, Event if this error occurred it continue to execute the method after passing 0 to all of the fields to this model instance.

Upvotes: 0

Views: 31

Answers (1)

Lycha
Lycha

Reputation: 10177

If I understand correctly you want to do something like this:

try:
  model_instance = AlertCount.objects.get(user=request.user.username)
  # Set your local fields here
except AlertCount.DoesNotExist:
  #Set your local fields here to zero

Upvotes: 2

Related Questions