繁体   English   中英

如何在测试 django-models 时处理 ManyToMany 字段?

[英]How to handle ManyToMany fields while testing django-models?

我正在尝试为我的 django 模型编写测试。 但是,我在测试 ManyToManyFields 时遇到问题,但尚未解决。

class TestVolunteeringModels(TestCase):
    def setUp(self) -> None:
        self.test_need = sample_need(title="Need", description="Description")
        self.test_opportunity = sample_opportunity(title="Opportunity", description="Description")
        for i in range(10):
            self.test_category = sample_category(name="Category")
            self.test_need.category = self.test_category
            self.test_opportunity.category = self.test_category

    def tearDown(self) -> None:
        self.test_need.delete()
        self.test_opportunity.delete()

这给我带来了这个错误:

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use category.set() instead.

问题是当我使用 .set() 时写在回溯指令中,如下所示:

self.test_need.category.set(self.test_category)
self.test_opportunity.category.set(self.test_category)

它给了我另一个错误,上面写着“TypeError: 'Category' object is not iterable”

所以我的问题是在这种情况下如何访问 ManyToMany 字段,以便我可以自由测试?

.set()需要一个可迭代的参数,但您传递的参数self.test_category是不可迭代的。 你有两个选择:

  • 使用.set([self.test_category,])而不是.set(self.test_category) 因此,您传递的是一个可迭代的列表,而不是一个不可迭代的 object(因此您会收到错误消息)。
  • 或者,您可以使用.add(self.test_category) function .add()将单个对象作为位置 arguments,并将它们添加到任何预先存在的类别中。

不过,您可能应该选择.set() ,因为这可以确保在其执行后,关联的类别集将恰好是您传递的类别。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM