当前位置: 首页 > 面试题库 >

如何以编程方式在Django中为给定模型生成CREATE TABLE SQL语句?

丁昌翰
2023-03-14
问题内容

我需要以编程方式在Django应用()中为给定的 非托管 模型生成CREATE TABLE语句managed = False

由于我正在使用旧数据库,因此我不想创建迁移并使用sqlmigrate

./manage.py sql命令对于此目的很有用,但已在Django 1.8中删除。

您知道其他选择吗?


问题答案:

如建议的那样,我对此案发表了完整的答案,这个问题可能暗示了这一点。

假设您有一个外部数据库表,您决定将其作为Django模型进行访问,因此将其描述为非托管模型(Meta: managed = False)。以后,您需要能够在代码中创建它,例如,使用本地数据库进行某些测试。显然,Django不会迁移非托管模型,因此不会在测试数据库中创建它。可以使用Django
API解决此问题,而无需使用原始SQL-
SchemaEditor。请参阅下面的更完整的示例,但作为一个简短的答案,您可以像这样使用它:

   from django.db import connections

   with connections['db_to_create_a_table_in'].schema_editor() as schema_editor:
        schema_editor.create_model(YourUnmanagedModelClass)

一个实际的例子:

# your_app/models/your_model.py

from django.db import models

class IntegrationView(models.Model):
    """A read-only model to access a view in some external DB."""

    class Meta:
        managed = False
        db_table = 'integration_view'

    name = models.CharField(
        db_column='object_name',
        max_length=255,
        primaty_key=True,
        verbose_name='Object Name',
    )
    some_value = models.CharField(
        db_column='some_object_value',
        max_length=255,
        blank=True,
        null=True,
        verbose_name='Some Object Value',
    )

    # Depending on the situation it might be a good idea to redefine
    # some methods as a NOOP as a safety-net.
    # Note, that it's not completely safe this way, but might help with some
    # silly mistakes in user code

    def save(self, *args, **kwargs):
        """Preventing data modification."""
        pass

    def delete(self, *args, **kwargs):
        """Preventing data deletion."""
        pass

现在,假设您需要能够通过Django创建此模型,例如用于某些测试。

# your_app/tests/some_test.py

# This will allow to access the `SchemaEditor` for the DB
from django.db import connections
from django.test import TestCase
from your_app.models.your_model import IntegrationView

class SomeLogicTestCase(TestCase):
    """Tests some logic, that uses `IntegrationView`."""

    # Since it is assumed, that the `IntegrationView` is read-only for the
    # the case being described it's a good idea to put setup logic in class 
    # setup fixture, that will run only once for the whole test case
    @classmethod
    def setUpClass(cls):
        """Prepares `IntegrationView` mock data for the test case."""

        # This is the actual part, that will create the table in the DB
        # for the unmanaged model (Any model in fact, but managed models will
        # have their tables created already by the Django testing framework)
        # Note: Here we're able to choose which DB, defined in your settings,
        # will be used to create the table

        with connections['external_db'].schema_editor() as schema_editor:
            schema_editor.create_model(IntegrationView)

        # That's all you need, after the execution of this statements
        # a DB table for `IntegrationView` will be created in the DB
        # defined as `external_db`.

        # Now suppose we need to add some mock data...
        # Again, if we consider the table to be read-only, the data can be 
        # defined here, otherwise it's better to do it in `setUp()` method.

        # Remember `IntegrationView.save()` is overridden as a NOOP, so simple
        # calls to `IntegrationView.save()` or `IntegrationView.objects.create()`
        # won't do anything, so we need to "Improvise. Adapt. Overcome."

        # One way is to use the `save()` method of the base class,
        # but provide the instance of our class
        integration_view = IntegrationView(
            name='Biggus Dickus',
            some_value='Something really important.',
        )
        super(IntegrationView, integration_view).save(using='external_db')

        # Another one is to use the `bulk_create()`, which doesn't use
        # `save()` internally, and in fact is a better solution
        # if we're creating many records

        IntegrationView.objects.using('external_db').bulk_create([
            IntegrationView(
                name='Sillius Soddus',
                some_value='Something important',
            ),
            IntegrationView(
                name='Naughtius Maximus',
                some_value='Whatever',
            ),
        ])

    # Don't forget to clean after
    @classmethod
    def tearDownClass(cls):
        with connections['external_db'].schema_editor() as schema_editor:
            schema_editor.delete_model(IntegrationView)

    def test_some_logic_using_data_from_integration_view(self):
         self.assertTrue(IntegrationView.objects.using('external_db').filter(
             name='Biggus Dickus',
         ))

为了使示例更完整…由于我们使用多个数据库(defaultexternal_db),Django会尝试在两个数据库上运行迁移以进行测试,到目前为止,数据库设置中没有任何选项可以阻止这种情况。因此,我们必须使用自定义的DB路由器进行测试。

 # your_app/tests/base.py

class PreventMigrationsDBRouter:
    """DB router to prevent migrations for specific DBs during tests."""
    _NO_MIGRATION_DBS = {'external_db', }

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """Actually disallows migrations for specific DBs."""
        return db not in self._NO_MIGRATION_DBS

并针对上述情况提供了一个测试设置文件示例:

# settings/test.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.oracle',
        'NAME': 'db_name',
        'USER': 'username',
        'HOST': 'localhost',
        'PASSWORD': 'password',
        'PORT': '1521',
    },
    # For production here we would have settings to connect to the external DB,
    # but for testing purposes we could get by with an SQLite DB 
    'external_db': {
        'ENGINE': 'django.db.backends.sqlite3',
    },
}

# Not necessary to use a router in production config, since if the DB 
# is unspecified explicitly for some action Django will use the `default` DB
DATABASE_ROUTERS = ['your_app.tests.base.PreventMigrationsDBRouter', ]

希望这个详细的,新的Django用户友好示例可以帮助某人并节省他们的时间。



 类似资料:
  • 问题内容: 我编写了python代码,以编程方式生成卷积神经网络(CNN),用于训练和验证caffe中的.prototxt文件。下面是我的功能: 有没有办法类似地生成deploy.prototxt以测试不在lmdb文件中的看不见的数据?如果是这样的话,如果有人可以给我提供参考,我将不胜感激。 问题答案: 很简单: 现在调用函数: 正如你可以看到有两处修改到prototxt(条件上是): 第一个,而

  • 问题内容: 我想为Java的玩具语言编写一个编译器。我想生成可运行的.class文件。我想知道执行此操作的最佳库或工具是什么?我知道我可以学习所有指令的二进制格式并建立自己的常量池等,但这似乎应该已经完成​​:没必要重新发明轮子,对吗? 在线搜索我发现了两种不同的Java汇编语言Jasmin和Jamaica,但是只有Jasmin看起来有所维护。 是否存在用于将字节码写入流的Java库?这是Apac

  • 问题内容: 给定2种rgb颜色和一个矩形区域,我想在这些颜色之间生成基本的线性渐变。我已经进行了快速搜索,唯一能够找到的是此Blog条目,但示例代码似乎丢失了,或者至少是在发布此信息之时。任何帮助,算法,代码示例,等等。这将用Java编写,但是显示层已经处理完毕,我只需要弄清楚如何弄清楚要显示的内容。 问题答案: 您需要在第一和第二种颜色之间进行插值。通过为每个分量(R,G,B)计算相同的插值,可

  • 在控制器中引用FactoryBean,然后。但是,对于这样一个简单的情况,我真的需要创建一个新类吗? 有一个工厂方法来构造托管bean。这个方法仍然存在显式实例化POJO的问题,因此它本身需要对它进行Spring注入。此外,这是完整的样板文件。 bean的构造非常琐碎,所以我认为Spring中有一种更简单的方法来完成它。有吗?

  • 演员系统是惊人的。我想知道我是否能使它更灵活地使用。 我有一系列相关的节点对(可以是文件的形式),比如: A-- 我想在服务器启动时以编程方式生成一个包含6种参与者(即a~F)的系统。而且他们有监督孩子的关系,就像上面提到的两个人。 这对阿克卡有可能吗? 编辑2014-05-28 抱歉搞混了。 我是阿克卡的新手,到目前为止我学到的一些概念可能并不那么准确。 真正的用例是,我想使用包含参与者之间关系

  • 问题内容: 我想为Jupyter笔记本中的班级写一份报告。我想计算一些东西,生成一些结果,并将它们包括在markdown中。我可以将单元格的输出设置为降价吗? 我想要这样的命令:生成phi符号,就像在markdown中一样。 换句话说,我想在markdown中制作一个模板,并插入由笔记本中编写的程序生成的值。重新计算笔记本应生成新结果,并插入新值并进行新的减价。使用此软件是否可能,或者我需要自己替