Django - 当使用不同的数据库时 - 我应该使用 "using" 还是 "db_manager"?

Django - when using different databases - should I use "using" or "db_manager"?

要select 一个特定的数据库,您可以编写:

Object.objects.using('other_db')...

或:

Object.objects.db_manager('other_db')...

两者似乎都运行良好。那么两者有什么区别呢?

编辑

我的意思是 - 我是否应该始终使用“db_manager('other_db')”,它涵盖了“”的所有情况使用('other_db')'语句?

这取决于你的情况。如果你不使用任何 manager method 那么 using() 就可以了,否则你将需要 db_manager().

You can select the database for a QuerySet at any point in the QuerySet “chain.” Just call using() on the QuerySet to get another QuerySet that uses the specified database.

但是如果你需要使用管理器方法,这将不起作用。

以下解释摘自docs:

假设您有一个接触数据库的自定义管理器方法 – User.objects.create_user()。因为 create_user() 是一个管理器方法,而不是 QuerySet 方法,所以你不能做 User.objects.using('another_db').create_user()create_user() 方法仅在管理器 User.objects 上可用,在从管理器派生的 QuerySet 对象上不可用。 解决方案是使用 db_manager(),像这样:

User.objects.db_manager('another_db').create_user(...)

db_manager() returns 绑定到您指定的数据库的管理器副本。