Django测试:DatabaseError:没有用于ManyToManyField的这样的表

bin*_*mac 6 python django unit-testing manytomanyfield

我为非常简单的博客应用程序编写了几个测试,但是当我运行测试时,多对多的关系失败了: ./manage.py test myblog

DatabaseError: no such table: myblog_post_tag
Run Code Online (Sandbox Code Playgroud)

然而当我这样做时./manage.py sql myblog:

BEGIN;
CREATE TABLE "myblog_tag" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" varchar(50) NOT NULL
)
;
CREATE TABLE "myblog_post_tag" (
    "id" integer NOT NULL PRIMARY KEY,
    "post_id" integer NOT NULL,
    "tag_id" integer NOT NULL REFERENCES "myblog_tag" ("id"),
    UNIQUE ("post_id", "tag_id")
)
;
CREATE TABLE "myblog_post" (
    "id" integer NOT NULL PRIMARY KEY,
    "title" varchar(200) NOT NULL,
    "pub_date" datetime NOT NULL,
    "content" text NOT NULL
)
;
COMMIT;
Run Code Online (Sandbox Code Playgroud)

它确实创建了一个表,但在测试时却没有这样做?任何帮助表示赞赏.这是我的测试:

class TagModelTest(TestCase):

    def test_create_tags_for_posts(self):
        # tests tagging posts, postodd will have tags 1 & 3, posteven will be 2 & 4
        postodd = Post(
            title="testing odd tags",
            pub_date=timezone.now(),
            content='''hello everybody, we are testing some tagging
                functionality here. This post should have odd tags.''',
        )
        posteven = Post(
            title="test even tags",
            pub_date=timezone.now(),
            content ='''hello everybody, we are testing some tagging
                functionality here. This post should have even tags.''',
        )
        #save them to db
        postodd.save()
        posteven.save()

        # create the  tags
        tag1 = Tag(name="1")
        tag2 = Tag(name="2")
        tag3 = Tag(name="3")
        tag4 = Tag(name="4")

        # save all tags to db
        tag1.save()
        tag2.save()
        tag3.save()
        tag4.save()

        # create the many2many relationship
        postodd.tag.add(tag1)
Run Code Online (Sandbox Code Playgroud)

我的models.py如果需要:

from django.db import models


class Tag(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name


class Post(models.Model):
    tag = models.ManyToManyField(Tag)
    title = models.CharField(max_length=200)
    pub_date = models.DateTimeField(verbose_name="Date published")
    content = models.TextField()

    def __unicode__(self):
        return self.title
Run Code Online (Sandbox Code Playgroud)

Bur*_*lid 1

./manage.py sql myblog不执行 SQL,它只是输出如果您运行 则它将syncdb执行的内容。

在这种情况下,您的数据库中似乎缺少该表。

如果这是对现有应用程序进行修改的结果;例如,您刚刚向模型添加了一个新字段;那么运行syncdb不会影响对数据库的更改。syncdb不执行任何破坏性操作(例如添加或删除表或列)。

在这种情况下,您可以手动运行查询来添加列;或者删除并使用 重新创建表syncdb

由于这是一个常见问题,大多数人都会使用数据迁移工具来south为您处理这些更改。南将明智地管理这些小变化。

  • 但我没有使用syncdb。现在我只运行测试,所以当我运行测试时,它不会创建一个测试数据库吗? (4认同)