如何将数据库中的模型实例保存到Django中? [英] How to get the database where a model instance was saved to in Django?

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

问题描述

我有一个使用多个数据库的django应用程序。给定一个模型的实例,如何获取存储在哪里的数据库(如果有的话)?我需要这个来保存另一个对象到第一个相同的数据库。

  def add_ducks_to_hunt(hunter ):
db =#the hunter's db
duck = Duck()
duck.save(using = db)


解决方案

使用 _state.db ,如:

  my_obj = MyModel.objects.get(pk = 1)
my_obj._state.db
/ pre>

这显示在路由示例


I have a django application using multiple databases. Given an instance of a model, how can I obtain the database where it is stored (if any)? I need this to save another object to the same database as the first.

def add_ducks_to_hunt(hunter):
    db = # the hunter's db
    duck = Duck()
    duck.save(using=db)

解决方案

Use _state.db, as in:

my_obj = MyModel.objects.get(pk=1)
my_obj._state.db

This is shown in the routing example.

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

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