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

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

问题描述



有没有办法指定一个模型(或app,even)应该只能使用一个特定的数据库?不想改变。我有两个数据库 - 默认是一个可以用于admin等的sqlite,还有一个是旧的。我使用inspectdb为旧数据库(的一部分)创建一个模型,它具有 managed = False 。但是有没有办法在模型本身中指定它只适用于特定的数据库?



我看到你可以指定 using = databasename / a>在某些查询集等,但这对于像 Databrowse (也可能是通用视图?)。它可能是Databrowse的一个短暂的,你不能指定数据库,但它似乎是正确的地方指定它是模型...



那么我以为也许这个答案是写一个自定义的模特经理只是指我的遗留数据库 - 但文档没有提到任何类似的东西。



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

解决方案

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



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


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

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?

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.

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天全站免登陆