python - 为具有多对多关系的 Django 模型编写测试

标签 python django testing django-models

我想为具有多对多关系的 Django 模型编写一个测试,但出现此错误:

ValueError: "< Tour: tour >" needs to have a value for field "id" before this many-to-many relationship can be used.

我的测试:

class ModelTestCase(TestCase):
    def setUp(self):
        self.mock_file = mock.MagicMock(File)
        self.mock_file.name = 'MockFile'
        self.before_count = Tour.objects.count()
        self.tour_agency = TourAgency.objects.create(
            name='agency',
            username='agency')
        self.tour_category = TourCategory.objects.create(name='category')
        self.tour_equipment = TourEquipment.objects.create(name='equipment')
        self.tour_leader = TourLeader.objects.create(
            name='leader',
            email='<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="acc0c9cdc8c9deecdfcdc1dcc0c982cfc3c1" rel="noreferrer noopener nofollow">[email protected]</a>',
            username='leader',
            bio='sample text',)
        self.tour_tag = TourTag.objects.create(name='tag')

    def test_model_can_create_tour(self):
        self.tour = Tour.objects.create(
            name='tour',
            description='description',
            summary='summary',
            agency=self.tour_agency,
            equipment=self.tour_equipment,
            category=self.tour_category,
            tags=self.tour_tag,
            activity_type='activity type',
            date=datetime.now,
            photo=self.mock_file)
        self.tour.save()
        self.tour.save_m2m()
        count = Tour.objects.count()
        self.assertNotEqual(self.before_count, count)

我将尝试使用 .save() 保存对象,但它不起作用。

最佳答案

在添加多对多关系之前,您首先需要保存游览模型。看代码我认为多对多是字段“tags”

def test_model_can_create_tour(self):
    self.tour = Tour.objects.create(
        name='tour',
        description='description',
        summary='summary',
        agency=self.tour_agency,
        equipment=self.tour_equipment,
        category=self.tour_category,
        activity_type='activity type',
        date=datetime.now,
        photo=self.mock_file)

    # Adding the tour later.
    self.tour.tags.add(self.tour_tag)
    count = Tour.objects.count()
    self.assertNotEqual(self.before_count, count)

这应该通过测试。

关于python - 为具有多对多关系的 Django 模型编写测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48706447/

相关文章:

django - 无法登录 Django 管理员

testing - 为什么 Selenium IDE 播放控件处于非事件状态? (如何运行记录的测试?)

python - 如何从 Python 中的以下数据类型中删除项目?

python - Django Auth 模型问题 - AUTH_USER_MODEL 未安装

python - Django 模型中的紧耦合

python - 如何在 python 中进行矩阵计算而不进行舍入?

mysql - 在 Heroku 上使用远程 MySQL 数据库与 Django 服务器

python - 在 Python 中使用 For 循环查找匹配值和总计

maven - 为什么 TestNG 会多次运行这些测试类?

debugging - Charles 网络调试代理未检测到 vpn 连接