Django测试错误: 关系不存在

8

我正在使用Python 3.3在Ubuntu 13.10上与Postgres一起使用Django 1.6。

我定义了一个模型User,如下所示:

from django.db import models
from django.contrib.auth.models import AbstractUser

from common.mixins import TimestampMixin


class User(TimestampMixin, AbstractUser):
    auth_key = models.CharField(max_length=16)

    def __str__(self):
        if self.first_name:
            if self.last_name:
                return "{0} {1}'s Profile".format(
                    self.first_name, self.last_name)
            else:
                return "{0}'s Profile".format(self.first_name)
        else:
            return "{0}'s Profile".format(self.username)

我有一个关于__str__的测试,如下:

from django.test import TestCase

from accounts.models import User
from common.tests.fixtureless import create_instance


class UserTest(TestCase):
    def test_str(self):
        initial = {
            'username': 'test_username',
            'first_name': 'test_first_name',
            'last_name': 'test_last_name',
        }
        user = create_instance(User, **initial)
        user.save()
        expected = "test_first_name test_last_name's Profile"
        self.assertEqual(user.__str__(), expected)
        user.delete()

        del(initial['last_name'])
        user = create_instance(User, **initial)
        user.save()
        expected = "test_first_name's Profile"
        self.assertEqual(user.__str__(), expected)
        user.delete()

        del(initial['first_name'])
        user = create_instance(User, **initial)
        user.save()
        expected = "test_username's Profile"
        self.assertEqual(user.__str__(), expected)
        user.delete()

我的测试套件只有大约20%的时间可以正常运行。但有时,我会遇到以下错误:

ERROR: test_str (blind_tiger.blind_tiger.apps.accounts.tests.UserTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/db/backends/util.py", line 53, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "accounts_user" does not exist
LINE 1: INSERT INTO "accounts_user" ("password", "last_login", "is_s...
                    ^


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/ricomoss/workspace/ses/blind_tiger/blind_tiger/settings/../apps/accounts/tests/models.py", line 18, in test_str
    user.save()
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/db/models/base.py", line 545, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/db/models/base.py", line 573, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/db/models/base.py", line 654, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/db/models/base.py", line 687, in _do_insert
    using=using, raw=raw)
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/db/models/manager.py", line 232, in _insert
    return insert_query(self.model, objs, fields, **kwargs)
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/db/models/query.py", line 1511, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/db/models/sql/compiler.py", line 898, in execute_sql
    cursor.execute(sql, params)
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/db/backends/util.py", line 53, in execute
    return self.cursor.execute(sql, params)
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/db/utils.py", line 99, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/utils/six.py", line 490, in reraise
    raise value.with_traceback(tb)
  File "/home/ricomoss/.virtualenvs/blind_tiger/lib/python3.3/site-packages/django/db/backends/util.py", line 53, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "accounts_user" does not exist
LINE 1: INSERT INTO "accounts_user" ("password", "last_login", "is_s...

这很让人沮丧,因为如果我在有问题的 user.save() 周围加上 try/except 以便检查对象,我就永远看不到这个错误。

从来没有出现过这个错误:

try:
    user.save()
except:
    raise Exception(user.__dict__)

有什么建议吗?

2
我不确定错误的原因是什么,但是顺便提一下,在Python 3中应该定义一个__str__方法,而不是__unicode__ - Alasdair
作为测试,重命名你的用户实现为其他名称可能值得一试,以防万一 Django 与 django.contrib.auth.models 中的 User 类混淆(虽然不应该这样...)。 - robjohncox
@robjohncox 这似乎不是问题所在。我将其重命名为BaseUser,但仍然出现相同的错误。如果那是问题所在,我会感到非常惊讶的。 - Rico
@rico 你用 South 迁移数据库吗? - eldos
2个回答

6

尝试运行以下命令:

python manage.py migrate --run-syncdb
python manage.py makemigrations appname
python manage.py migrate

包括应用程序名称就像规则一样。 - Lord-shiv

4

我解决了这个问题。先尝试运行以下命令:

python manage.py syncdb

2
不知道为什么你因为那个评论失去了一分,但我也遇到了同样的问题,这个方法对我也有效。尽管对于Django 1.7及以上版本,请使用migrate而不是syncdb。 - oenpelli
1
实际上,“manage.py test”不需要运行“migrate”,因为它在不同的测试数据库上工作,并且应该自动在该测试数据库上运行迁移。然而,我也遇到了同样的问题(当常规数据库为空时测试失败,这与测试数据库无关),所以令人恼火的是,出于某种原因,这是一个解决方案。 - Risadinha
2
我收到了这个消息:未知命令:'syncdb'。你是不是想说'syncdata'? - merhoo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接