匹配的查询不存在,django,django-tests"/>

首页 > 解决方案 > 命令行中的Django测试错误:匹配的查询不存在

问题描述

这是我的tests.py文件:

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

class ArticleTestCase(TestCase):

    @classmethod
    def setup(self):
        Article.objects.create(
            article_title="title1",
            article_content="content of article",
        )

    def test_article_title(self):
        a1 = Article.objects.get(pk=1)
        article_name = a1.article_title
        self.assertEquals(article_name, 'title1')

但是,我总是收到这个错误:

Traceback (most recent call last):
File "F:\Django_Blog_Live\swagato_blog_site\blog_api\tests.py", line 16, in test_article_title
a1 = Article.objects.get(pk=1)
File "F:\Django_Blog_Live\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
File "F:\Django_Blog_Live\env\lib\site-packages\django\db\models\query.py", line 415, in get
raise self.model.DoesNotExist(
blog_api.models.Article.DoesNotExist: Article matching query does not exist.

并且错误描述指向这个语句:a1 = Article.objects.get(pk=1)

我究竟做错了什么?

标签: djangodjango-tests

解决方案


setup不是该方法的正确名称。正确的名称是setUp(注意大写U)。它不是一个classmethod.

还有另setUpClass一种方法称为classmethod.

两者之间的区别在于setUp在每个测试方法之前运行,而setUpClass对整个测试用例运行一次。

用法

使用setUp方法很简单:

class ArticleTestCase(TestCase):
    def setUp(self):
        # create objects
        # ...

在 Django 中,如果你使用setUpClass,你还需要super调用父类:

class ArticleTestCase(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass() # call parent

        # create objects
        # ...

推荐阅读