From 833a7a877e22833e80b986a21a7fdafc3b032fa9 Mon Sep 17 00:00:00 2001 From: Charles Shin Date: Thu, 23 Feb 2017 19:01:21 -0800 Subject: [PATCH] Fixed duplicate UserResponse added bug and added unique constraint on UserResponse --- .../core/migrations/0008_auto_20170224_0259.py | 18 ++++++++++++++++++ edivorce/apps/core/models.py | 3 +++ edivorce/apps/core/utils/user_response.py | 16 ++++++---------- 3 files changed, 27 insertions(+), 10 deletions(-) create mode 100644 edivorce/apps/core/migrations/0008_auto_20170224_0259.py diff --git a/edivorce/apps/core/migrations/0008_auto_20170224_0259.py b/edivorce/apps/core/migrations/0008_auto_20170224_0259.py new file mode 100644 index 00000000..b9dc8699 --- /dev/null +++ b/edivorce/apps/core/migrations/0008_auto_20170224_0259.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('core', '0007_auto_20170210_1702'), + ] + + operations = [ + migrations.AlterUniqueTogether( + name='userresponse', + unique_together=set([('bceid_user', 'question')]), + ), + ] diff --git a/edivorce/apps/core/models.py b/edivorce/apps/core/models.py index f64b082a..d76d08ba 100644 --- a/edivorce/apps/core/models.py +++ b/edivorce/apps/core/models.py @@ -119,6 +119,9 @@ class UserResponse(models.Model): value = models.TextField(blank=True) """ The question's response from the user """ + class Meta: + unique_together = ("bceid_user", "question") + def __str__(self): return '%s -> %s' % (self.bceid_user, self.question.key) diff --git a/edivorce/apps/core/utils/user_response.py b/edivorce/apps/core/utils/user_response.py index 5ca13262..289f8ff2 100644 --- a/edivorce/apps/core/utils/user_response.py +++ b/edivorce/apps/core/utils/user_response.py @@ -47,15 +47,11 @@ def copy_session_to_db(request, bceid_user): for q in questions: if request.session.get(q.key) is not None: # copy the response to the database - if UserResponse.objects.filter(bceid_user=bceid_user, question=q).exists(): - UserResponse.objects.update(bceid_user=bceid_user, - question=q, - value=request.session.get(q.key)) - else: - UserResponse.objects.create(bceid_user=bceid_user, - question=q, - value=request.session.get(q.key)) + UserResponse.objects.update_or_create( + bceid_user=bceid_user, + question=q, + defaults={'value': request.session.get(q.key)}, + ) - - # clear the response from the session + # clear the response from the session request.session[q.key] = None