程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Django 测试失败,<model> 没有属性“对象”错误大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Django 测试失败,<model> 没有属性“对象”错误?

开发过程中遇到Django 测试失败,<model> 没有属性“对象”错误的问题如何解决?下面主要结合日常开发的经验,给出你关于Django 测试失败,<model> 没有属性“对象”错误的解决方法建议,希望对你解决Django 测试失败,<model> 没有属性“对象”错误有所启发或帮助;

我有以下两种型号:

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'

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

解决方法

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

大佬总结

以上是大佬教程为你收集整理的Django 测试失败,<model> 没有属性“对象”错误全部内容,希望文章能够帮你解决Django 测试失败,<model> 没有属性“对象”错误所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: