Django 测试失败,出现 <model> 没有属性 'object' 错误

Django tests fails with <model> has not attribute 'object' error

我有以下两个模型:

class Resource(models.Model):
    identifier = models.UUIDField(default=uuid.uuid4, unique=True)
    date_added = models.DateTimeField(default=now)

    def __repr__(self):
        return f'Resource: {self.identifier}, Time added: {self.date_added}'

class URLResource(Resource):
    url = models.URLField()

    def __repr__(self):
        return f'{self.identifier} URL: {self.url}'

当我 运行 在 django shell 中执行以下命令时,一切正常:

> from user_page.models import URLResource
> URLResource.objects.create(url='abc') 
# outputs: `a3157372-7191-4d70-a4b1-c6252a2a139c URL: abc`
> URLResource.objects.get(url='abc') 
# outputs: `a3157372-7191-4d70-a4b1-c6252a2a139c URL: abc`

然而,我看似微不足道的测试用例失败了,即使在 django 中类似的执行成功了 shell:

from django.test import TestCase
from users.models import CustomUser
from .models import Resource, URLResource, Record

class URLResource(TestCase):
    def setUp(self):
        url_resource = URLResource.objects.create(url='abc')
        print(repr(url_resource))

    def test_url(self):
        print(repr(URLResource.objects.get(url='abc')))

我收到以下错误:

======================================================================
ERROR: test_url (user_page.tests.URLResource)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/admin/Desktop/readrrr/user_page/tests.py", line 26, in setUp
    url_resource = URLResource.objects.create(url='abc')
AttributeError: type object 'URLResource' has no attribute 'objects'

----------------------------------------------------------------------

您已将测试 class 命名为与您尝试测试的 class 相同的名称。尝试将其重命名为 URLResourceTest