Django 2测试:无法获取创建的对象进行测试 [英] Django 2 Test: Created object cannot be gotten for tests
本文介绍了Django 2测试:无法获取创建的对象进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经读过有关从测试开始构建程序的知识,所以我想尝试一下.我已经完成了初始的 project
和 app
和 model
,但是当我尝试运行测试时,出现了不存在""错误.我已经运行了迁移,在可以运行测试之前,还有更多要做的事情吗?这是我的代码:
I've read about building programs starting with tests, so I thought I'd give it a shot. I've made my initial project
and app
and a model
, but when I try to run a test, I get a "Does not exist" error. I've run the migrations, is there more I have to do before I can run a test? Here's my code:
models.py
models.py
from django.db import models
class Name(models.Model):
first_name = models.CharField(
"First Name",
max_length=100,
)
middle_name = models.CharField(
"Middle Name or Initial",
max_length=100,
default='',
)
last_name = models.CharField(
"Last Name",
max_length=200,
)
def __str__(self):
return f'{self.last_name}, {self.first_name}'
tests.py
from django.test import TestCase
from contacts.models import Name
class TestNameModel(TestCase):
@classmethod
def setupTestData(cls):
Name.objects.create(first_name='Banny', last_name='Banvil')
def test_name_exists(self):
name = Name.objects.get(id=1)
print (name)
还有我得到的错误:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_name_exists (contacts.tests.TestNameModel)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/CrazyCarl/Software/contact/contacts/tests.py", line 12, in test_name_exists
name = Name.objects.get(id=1)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 403, in get
self.model._meta.object_name
contacts.models.DoesNotExist: Name matching query does not exist.
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (errors=1)
Destroying test database for alias 'default'...
我尝试在终端中制作一个对象,以查看其是否正常工作:
I tried making an object in the terminal to see if it was working:
>>>from contacts.models import Name
>>>Name.objects.create(last_name='John', first_name='Smith')
<Name: John, Smith>
>>>Name.objects.all()
<QuerySet [<Name: John, Smith>]>
>>>n = Name.objects.get(id=1)
>>>print (n)
John, Smith
我想念什么?
推荐答案
它是 setUpTestData
而不是 setupTestData
这篇关于Django 2测试:无法获取创建的对象进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文