Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do catch A 'UNIQUE constraint failed' 404 in django

Tags:

python

django

How do I specifically catch a UNIQUE constraint failed 404 in the following code, I know I have to add something in the ( here? ) section

try:     q = AnswerModel(user=user, yes_question=question_model)     q.save() except ( here? ):     return HttpResponseRedirect('/user/already_exists') 
like image 401
Sprig Mendle Avatar asked Jan 01 '15 08:01

Sprig Mendle


People also ask

How do you handle unique constraint error?

To handle unique constraint violations: Catch uniqueness exceptions thrown by the database at the lowest level possible — in the UnitOfWork class. Convert them into Result. Use the UnitOfWork in the controller to explicitly commit pending changes and see if there are any uniqueness constraint violations.

What is unique constraint in Django?

New in Django 4.0. Positional argument *expressions allows creating functional unique constraints on expressions and database functions. creates a unique constraint on the lowercased value of the name field in descending order and the category field in the default ascending order.

What is integrity error in Django?

This means that your DB is expecting that field to have a value. So when it doesn't you get an error. null. If True, Django will store empty values as NULL in the database. Default is False.


2 Answers

from django.db import IntegrityError  except IntegrityError: 

This is what you need.

EDITED for @mbrochh:

from django.db import IntegrityError  except IntegrityError as e:      if 'unique constraint' in e.message: # or e.args[0] from Django 1.10         #do something 

Yes, you can be more precise but in question case UNIQUE failed is highly likely.

like image 107
torm Avatar answered Sep 30 '22 18:09

torm


IMHO, I would recommend to resolve this situation by get_or_create().

new_obj, created = AnswerModel.objects.get_or_create(user=user, yes_question=question_model) if created:     do_something_for_new_object(new_obj) else:     logging.error("Duplicated item.")     return
like image 22
Walter Liu Avatar answered Sep 30 '22 17:09

Walter Liu