Django引发IntegrityError:UNIQUE约束在单元测试中失败

时间:2017-06-17 16:54:10

标签: python django

当我尝试在test.py或shell界面中创建Timesheet对象时,出现完整性错误。但是,我可以通过服务的html界面创建对象就好了。下面的错误,模型,视图和表单。

非常感谢任何想法或建议。

错误:

    Traceback (most recent call last):
  File "<console>", line 5, in <module>
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/query.py", line 399, in create
    obj.save(force_insert=True, using=self.db)
  File "/Users/Development/et/timesheets/models.py", line 222, in save
    return super(Timesheet, self).save(*args, **kwargs)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/base.py", line 796, in save
    force_update=force_update, update_fields=update_fields)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/base.py", line 824, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/base.py", line 908, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/base.py", line 947, in _do_insert
    using=using, raw=raw)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/query.py", line 1045, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql
    cursor.execute(sql, params)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
    return Database.Cursor.execute(self, query, params)
IntegrityError: UNIQUE constraint failed: timesheets_timesheet.id

型号:

class Timesheet(models.Model):
    owner = models.ForeignKey(User, editable=False)

    employee = models.CharField(
        max_length=30,
        help_text='Name of the employee that did the work'
    )

    company = models.CharField(
        max_length=30,
        help_text = 'Name of the company that will pay for the invoice'
    )

    date = models.DateField(help_text='Week-End Date (Sunday)', validators=[validate_sunday])

    ...Other model fields...

    secret = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)


    ...Other model functions...

    def save(self, *args, **kwargs):
        self.full_clean()

        if self.pk is None:
            super(Timesheet, self).save(*args, **kwargs)
            self.create_time_entries()
        else:
            self.update_hours()
        return super(Timesheet, self).save(*args, **kwargs)

查看:

class TimesheetCreate(LoginRequiredMixin, CreateView):
    model = Timesheet
    template_name = 'timesheet.html'
    form_class = TimeSheetForm

    def form_valid(self, form):
        form.instance.owner = self.request.user
        return super(TimesheetCreate, self).form_valid(form)

    def get_success_url(self):
        return reverse('TimeEntryUpdate', args=(self.object.pk,))

表单:

class TimeSheetForm(forms.ModelForm):
    employee = forms.CharField(label='Name',
                               widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Your Name'}))
    company = forms.CharField(label='Company',
                              widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Company'}))
    date = forms.DateField(label='Date',
                           input_formats=date_formats,
                           widget=forms.DateInput(format='%d %B, %Y', attrs={'class' : 'form-control datepicker-sunday-only', 'placeholder' : 'Week-end Date (Sunday)'}),
                           error_messages={'invalid': 'Date must be a Sunday!'})

    class Meta:
        model = Timesheet
        fields = ['employee', 'company', 'date']
        exclude = ['owner', 'secret', 'employer_name', 'employer_email']

    def __init__(self, *args, **kwargs):
        super(TimeSheetForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance.status in ('1','2','3',) :
            self.fields['employee'].widget.attrs['readonly'] = True
            self.fields['company'].widget.attrs['readonly'] = True
            self.fields['date'].widget.attrs['readonly'] = True

1 个答案:

答案 0 :(得分:1)

您正在调用保存方法两次,编辑保存方法,

def save(self, *args, **kwargs):
    self.full_clean()

    if self.pk is None:
        super(Timesheet, self).save(*args, **kwargs)
        self.create_time_entries()
    else:
        self.update_hours()
        super(Timesheet, self).save(*args, **kwargs)