RelatedObjectDoesNotExist

时间:2016-07-18 15:11:15

标签: python django django-testing django-tests

我正在测试名为Authenticator的django模型,Authenticator模型有一个包含ManyToManyField和OneToOneField的字段。 当我测试模型时,我得到了RelatedObjectDoesNotExist和ValueError:无法分配"''":" Authenticator.authenticator"必须是"用户"实例

这是我的模特

class Authenticator(models.Model):
    orders                   =      models.ManyToManyField('client.Order', related_name = 'order_set')
    authenticator            =      models.OneToOneField(User, on_delete = models.CASCADE)
    weight                   =      models.IntegerField(default = 0)
    percentage_accuracy      =      models.FloatField("Nearness to aggregate score", default=0)
    date_assigned            =      models.DateTimeField(default = timezone.now)
    job_count                =      models.IntegerField(default = 0)
    percentage_consistency   =      models.FloatField(default = 0)


    def __unicode__(self):
        return '%s' %(self.authenticator.username)

我的测试代码是

from django.test import TestCase
from .models import User, Authenticator

class EntryModelTest(TestCase):
    def test_string_representation_for_authenticator(self):
        auth = Authenticator(authenticator = "matt")
        print "Auth: ", auth
        consistency_weight = Authenticator(weight = "0")
        print "Consistency Weight: ", consistency_weight
        self.assertEqual(str(auth), auth.authenticator)
        self.assertEqual(int(consistency_weight), consistency_weight.weight)

1 个答案:

答案 0 :(得分:1)

在行中:

auth = Authenticator(authenticator = "matt")

您尝试使用" Authenticator"初始化authenticator财产价值"matt"。由于您声明此属性应为用户模型,因此您应在此处分配User实例。类似的东西:

auth = Authenticator(authenticator=User(name="matt"))

可能更接近你想要做的事情(显然我不知道你的用户模型的结构)。

除此之外,还有一些未经请求的编码建议:

  • 使用PEP8
  • 作为authenticator属性的名称Authenticator令人困惑; user可能在这里更有意义,因为它是此身份验证器的用户属性
  • 避免打印语句并在单个测试中测试多个断言
  • __unicode__方法中访问另一个模型会引入两个问题 - 它会导致数据库查找,这可能会产生N + 1个场景,并且更有可能抛出错误,这将使字符串表示为此模型在这种情况下无法使用且复杂的调试/记录