Django如何使用连接创建的符号

2024-07-04 08:44:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道何时连接到我的Django数据库,或者何时重启Django服务器。我找到了connection_createdDjango信号。描述如下:

Sent when the database wrapper makes the initial connection to the database. This is particularly useful if you’d like to send any post connection commands to the SQL backend.

所以我想用这个信号对我的案子来说是个很好的解决办法。我想在建立连接后运行一个函数。我找不到任何关于这个信号用例的文档。connection_created.connect可能是要使用的函数。此函数接受一组参数,但相关的参数是selfreceiversender和{}。有人知道我如何使用这些参数和这个函数在一个新的连接实例上运行我的函数吗?在

另外,如果有人除了这个信号还有其他的解决方案,我很乐意听听。在


Tags: thetodjango函数服务器数据库参数信号
2条回答

我将所有表分布在动态postgres表模式中,并使用连接信号来设置连接的搜索路径,因为django不支持postgres模式。在

myapp/apps.py

from django.db.backends.signals import connection_created

class MyappConfig(AppConfig):
    name = 'myapp'
    def ready(self):
        from myapp.schema_manager import new_connection
        connection_created.connect(new_connection)

myapp/schema_manager.py

^{pr2}$

根据the docs,此信号接收两个参数:

sender

The database wrapper class – i.e. django.db.backends.postgresql.DatabaseWrapper or django.db.backends.mysql.DatabaseWrapper, etc.

connection

The database connection that was opened. This can be used in a multiple-database configuration to differentiate connection signals from different databases.

... since django does not support postgres schemas

Django支持postgres模式:

class MyModel(models.Model):
    id = models.IntegerField(primary_key=True)
    title = models.TextField()

    class Meta:
        db_table = '"schema_name"."table_name"'

我在我们所有的项目中都使用这个符号。在

相关问题 更多 >

    热门问题