当我尝试运行单元测试时遇到问题。 为什么会给我该错误消息?
来自tests.py的代码:
class CourseTestCase(TestCase):
def create_category(name="English", imgpath="ImgPath"):
return Category.objects.create(name=name, imgpath=imgpath)
def setUp(self):
Course.objects.create(
name='English',
description='Sample text',
category_id=self.create_category().id,
logo='Logo'
)
def test_course_category(self):
english = Course.objects.get(name='English')
self.assertEqual(english.category_id, 1)
Models.py:
class Category(models.Model):
name = models.CharField(max_length=64)
imgpath = models.CharField(max_length=64)
def __str__(self):
return str(self.name)
class Course(models.Model):
name = models.CharField(max_length=64)
description = models.TextField()
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False)
logo = models.TextField()
def __str__(self):
return str(self.name)
ValueError:无法分配“'Category'”:“ Course.category”必须是“ Category”实例。
答案 0 :(得分:1)
尝试以下代码
class CourseTestCase(TestCase):
def setUp(self):
self.category = Category.objects.create(name="English", imgpath="ImgPath")
self.course = Course.objects.create(
name='English',
description='Sample text',
category=self.category,
logo='Logo'
)
def test_course_category(self):
english = Course.objects.get(name='English')
self.assertEqual(english.category_id, self.category.id)
答案 1 :(得分:0)
只需更改此:
category_id=self.create_category().id,
对此:
category=self.create_category(),
错误ValueError: Cannot assign "'Category'": "Course.category" must be a "Category" instance.
告诉您属性category
期望的是Category
的类实例,而不是他的id
的类实例