发送多个发布请求时的IntegrityError

时间:2018-03-27 19:43:53

标签: django reactjs django-models django-views

我发送了每个标签的发布请求

前端在这里:

handleOnClick() {
        const { resource, csrf } = this.props;
        let postFunc = (ele) => {
            const label = ele.label.toLowerCase()
            request
                .post(`/bookmarks/groups/${label}`)
                .set('X-CSRFToken', csrf)
                .send(resource.id).then(() => {
                    console.log('we did it')
                })
        }
        _(this.state.multiValue).forEach(postFunc)

两个帖子请求似乎都提供了,但是在第一次获取和完整性错误之后的任何一个。

我的观点:

def post(self, request, slug):
    """Create a bookmark of the resource for the current user."""
    # print request.user
    to_add = Resource.objects.get(id=int(request.body))
    try:
        bm = Bookmark.objects.get(resource=to_add)
    except Bookmark.DoesNotExist:
        bm = Bookmark.objects.create(user=request.user, resource=to_add)
    bookmark_group = BookmarkGroup.objects.get(name=slug)
    bookmark_group.bookmarks.add(bm)
    return JsonResponse({}, status=201, safe=False)

我基本上是在检查是否存在书签,如果它没有创建它。

书签和群组模型:

class Bookmark(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    resource = models.ForeignKey("Resource", on_delete=models.CASCADE, related_name="bookmarks")
    # meta
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('user', 'resource',)
        ordering = ('resource',)

    def __str__(self):
        return "{} | {}".format(self.user, self.resource)

class BookmarkGroup(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(null=False, unique=True)
    bookmarks = models.ManyToManyField(Bookmark, related_name='bookmarks', blank=True)
    def __str__(self):
        return self.name

我已经包含了堆栈跟踪,如果需要可以包含更多代码:

Traceback (most recent call last):
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/path/to/my/app/views/bookmark_group.py", line 37, in post
    bm = Bookmark.objects.create(user=request.user, resource=to_add)
  File "/Users/path/to/my/venv/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/path/to/my/venv/lib/python2.7/site-packages/django/db/models/query.py", line 394, in create
    obj.save(force_insert=True, using=self.db)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/base.py", line 806, in save
    force_update=force_update, update_fields=update_fields)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/base.py", line 836, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/base.py", line 922, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/base.py", line 961, in _do_insert
    using=using, raw=raw)
  File "/Users/path/to/my/venv/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/path/to/my/venv/lib/python2.7/site-packages/django/db/models/query.py", line 1061, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1099, in execute_sql
    cursor.execute(sql, params)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/debug_toolbar/panels/sql/tracking.py", line 164, in execute
    return self._record(self.cursor.execute, sql, params)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/debug_toolbar/panels/sql/tracking.py", line 106, in _record
    return method(sql, params)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute
    return self.cursor.execute(query, args)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
    self.errorhandler(self, exc, value)
  File "/Users/path/to/my/venv/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
IntegrityError: (1062, "Duplicate entry '1-2728' for key 'app_bookmark_user_id_resource_id_a01d1abf_uniq'")

1 个答案:

答案 0 :(得分:1)

从你的追溯这一行引起异常,
bm = Bookmark.objects.create(user=request.user, resource=to_add)由于您定义了unique_together = ('user', 'resource',),因此发生错误。

我建议您更改views.py,如下所示

def post(self, request, slug):
    """Create a bookmark of the resource for the current user."""
    to_add = Resource.objects.get(id=int(request.body))

    # Changes starts    
    bm, created = Bookmark.objects.get_or_create(user=request.user, resource=to_add)

    bookmark_group = BookmarkGroup.objects.get(name=slug)
    bookmark_group.bookmarks.add(bm)
    return JsonResponse({}, status=201, safe=False)



或者你可以简单地改变, bm = Bookmark.objects.get(resource=to_add)bm = Bookmark.objects.get(resource=to_add,user=request.user)