Django - 如何为模型指定数据库? [英] Django - how to specify a database for a model?

查看:29
本文介绍了Django - 如何为模型指定数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法指定一个模型(或应用程序,甚至)应该只使用一个特定的数据库?

Is there a way to specify that a model (or app, even) should only ever use one particular database?

我正在使用不想更改的旧数据库.我有两个数据库——默认"是一个可用于管理员等的 sqlite 数据库,另一个是旧数据库.我使用inspectdb为(部分)遗留数据库创建了一个模型,它有managed = False.但是有没有办法在模型本身中指定它只适用于特定的数据库?

I am working with a legacy database that I don't want to change. I have two databases - the 'default' is an sqlite one that could be used for admin etc, and the legacy one. I used inspectdb to create a model for (part of) the legacy database, and it has managed = False. But is there a way to specify in the model itself that it only applies to a particular database?

我看到你可以在某些查询集等中指定 using=databasename 但这对 Databrowse(可能还有通用视图?).无法指定数据库可能是 Databrowse 的一个缺点,但似乎指定它的正确位置是模型...

I see that you can specify using=databasename in some query sets etc but this is no good for things like Databrowse (and possibly also generic views?). It might be a short-coming of Databrowse that you can't specify a database, but it just seems like the right place to specify it is the model...

然后我想也许答案是编写一个自定义的模型管理器 仅指我的旧数据库 - 但文档没有提到类似的内容.

Then I thought maybe the answer is to write a custom model manager that only refers to my legacy database - but the docs don't mention anything like that.

对于 Django 世界,我是否只是对如何使用多个数据库有不同的心理模型?

Do I just have a different mental model of how multiple databases might be used, to the Django world?

推荐答案

据我所知你不能直接用模型指定数据库,因为它会阻止应用程序被重用,但从我可以在文档中看到:

As far as I know you can't specify the database directly with the model since it would kind of prevent the app from ever being reusable, but from what I can see in the docs:

https://docs.djangoproject.com/en/1.8/topics/db/multi-db/

这篇关于Django - 如何为模型指定数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆