一个django模型知道从哪个数据库加载,以及如何访问这个信息? [英] Does a django model know from which database it was loaded and how can this info be accessed?

查看:114
本文介绍了一个django模型知道从哪个数据库加载,以及如何访问这个信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,例如,我们有这个代码:

  for myapp.models.Book.objects.using( 'alternate_database')。all():
#...
book.save()

将书保存到'alternate_database''default'一个?如果他们被保存到另一个,那么模型似乎知道从哪个数据库加载。



这个信息存储在哪里?如何从模型中获取数据库名称?

解决方案

好的,这里是正确的答案。数据库名称保存在 db 字段中的 ModelState 类中,该字段在 Model中进行了实例化。 _state



所以,就像上面的例子一样:



<$ p $全部():
打印book._state.db #output:'alternate_database'
book.save()
print book._state.db #output:'alternate_database'


So, for instance, we have this code:

for book in myapp.models.Book.objects.using('alternate_database').all():
    #...
    book.save()

Would be books saved to 'alternate_database' or to the 'default' one? If they would be saved to an alternate one, then models seem to be aware from which databases they are loaded from.

Where this informtion is stored? How can i get database name from a model?

解决方案

Okay, here is the right answer. The database name is saved in ModelState class in db field, which is instantciated in Model._state

So, it goes like this for the example above:

for book in myapp.models.Book.objects.using('alternate_database').all():
    print book._state.db #output: 'alternate_database'
    book.save()
    print book._state.db #output: 'alternate_database'

这篇关于一个django模型知道从哪个数据库加载,以及如何访问这个信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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