gpt4 book ai didi

python - 如何在 Django 测试期间使用 managed = False 创建表

转载 作者:IT老高 更新时间:2023-10-28 21:58:35 31 4
gpt4 key购买 nike

我有一个 managed = False 的模型。

class SampleModel(models.Model):
apple = models.CharField(max_length=30)
orange = models.CharField(max_length=30)

class Meta:
managed = False

我有一个创建 SampleModel 的单元测试,但是当我运行测试时,我得到:

DatabaseError: no such table: SAMPLE_SAMPLE_MODEL

django 文档 - https://docs.djangoproject.com/en/dev/ref/models/options/#managed记录以下内容:

For tests involving models with managed=False, it's up to you to ensure the correct tables are created as part of the test setup.

如何在测试设置期间实际“创建”表?或者,我怎样才能使它在我运行测试时,这个模型在测试期间具有“managed = True”?

在实际应用中,这个模型实际上是由数据库中的一个 View 支持的。但是在测试期间,我想把它当作一个表格,并能够在其中插入测试数据。

最佳答案

您可以使用 SchemaEditorTestCase.setUp使用 managed = False 显式创建模型的方法。

# models.py

from django.db import models


class Unmanaged(models.Model):
foo = models.TextField()

class Meta:
# This model is not managed by Django
managed = False
db_table = 'unmanaged_table'

在你的测试中:

# tests.py

from django.db import connection
from django.test import TestCase

from myapp.models import Unmanaged


class ModelsTestCase(TestCase):
def setUp(self):
super().setUp()

with connection.schema_editor() as schema_editor:
schema_editor.create_model(Unmanaged)

if (
Unmanaged._meta.db_table
not in connection.introspection.table_names()
):
raise ValueError(
"Table `{table_name}` is missing in test database.".format(
table_name=Unmanaged._meta.db_table
)
)

def tearDown(self):
super().tearDown()

with connection.schema_editor() as schema_editor:
schema_editor.delete_model(Unmanaged)

def test_unmanaged_model(self):
with self.assertNumQueries(num=3):
self.assertEqual(0, Unmanaged.objects.all().count())
Unmanaged.objects.create()
self.assertEqual(1, Unmanaged.objects.all().count())

关于python - 如何在 Django 测试期间使用 managed = False 创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7020966/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com