python - Django:IntegrityError:列 user_id 不是唯一的

标签 python django

我想测试一些使用用户对象的东西。

但出于某种原因我得到:

IntegrityError: column user_id is not unique

我用头撞墙已经有一段时间了,似乎我无法弄清楚哪里出了问题。起初我以为数据库可能没有在测试之间刷新,但我跟踪了 User.objects.all() 并且它是一个空列表。

这是测试:

from django.contrib.auth.models import User
from django.test import TestCase

class TestSomething(TestCase):
    def test_create_user(self):
        User.objects.create_user('foo', 'foo@bar', 'bar')

我的测试设置:

from settings import *

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', 
        'NAME': ':memory:',
    }
}

TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'

更新:

我应该更好地阅读我的跟踪记录。实际上是以下信号导致了问题。

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile(user=instance).save()

最佳答案

我通过这样调整我的信号解决了这个问题:

from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.get_or_create(user=instance)

这解决了症状,但并没有真正解决问题。我认为将正常测试与 Django 测试混合会在某处导致错误。当我单独在我的问题中运行测试时,它会起作用。

如果我没有得到其他答案,我会将这个答案标记为正确。

关于python - Django:IntegrityError:列 user_id 不是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6388105/

相关文章:

python - 在 Windows 7 上的 wamp apache 中安装 python cgi

python - Matplotlib,绘制 pandas 系列 : AttributeError: 'tuple' object has no attribute 'xaxis'

django - 在 Django Rest Framework 中使用 APIView 和 viewset 设置路由器

python - Django 重复检测冗余迁移

python - django 1.5 ModelForm 中的 "This field cannot be null"错误

python - 如何执行从特定代码行开始的 python 文件?

python - 如何编写 Perl、Python 或 Ruby 程序来更改 Windows 上另一个进程的内存?

python - Base 62 转换

django - 如何从查询集中创建选择字段并在表单中实现它

python - 我们可以使用 reportlab 创建交互式 PDF 表单吗?