从现有的MongoDB数据库创建Django模型 [英] Django model creation from existing MongoDB databases

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

问题描述

我在MongoDB中有几个数据库,我想要动态创建模型,因为有很多数据库,我不能手动执行。问题:


  1. 我的models.py应该是什么样子的? (是否inspectdb可以使用mongodb数据库或仅基于SQL的dbs?)

  2. 由于数据库模型是动态创建的,我如何编写序列化器类以返回动态字段?

提前感谢

解决方案

Django支持一种针对传统关系数据库的对象关系映射器。虽然 Django有许多mongodb软件包,但他们都不支持 inspectdb 来构建模型。无论哪种方式, inspectdb 是一个kludge 被设计为一个过程,帮助一个迁移离开遗留系统,即您将构建您的 models.py 文件一次,从不再次运行 inspectdb 。这不是你想要做的,因为你似乎想要在运行时可以添加或更改的动态模型。



在明亮的一面, Django MongoDB Engine 有一些支持 内的任意嵌入式模型定义的模型。但是即使如此,他们似乎也不太支持它:


正如你所看到的,通用嵌入式模型增加了很多开销您的数据记录。如果你想使用它们,那么你可以这样做...


总之,尝试建立你的模型最好你可以实际匹配你的要求。如果在生产前没有任何关于您的模型的信息,那么Django也不是正确的解决方案。


I have a few databases in MongoDB that I want to create models for dynamically, since there are many databases and I cannot do it manually. Questions:

  1. What should my models.py look like? (Does inspectdb work with mongodb databases or only SQL based dbs?)
  2. Since the database models are created dynamically, how do I code the serializer class to return the dynamic fields?

Thanks in advance.

解决方案

Django supports an object-relational mapper, that is aimed at traditional relational databases. While there are a number of mongodb packages for Django, none of them support inspectdb to construct your models. Either way, inspectdb is a kludge designed as a one of process to help a one-of migratation away from a legacy system, i.e. you'd build your models.py file once and never run inspectdb again. This is not what you want to do, as you seem to want dynamic models that can be added or altered at runtime.

On the bright side, Django MongoDB Engine has some support for arbitrary embedded models within pre-defined models. But even then they don't seem too supportive of it:

As you can see, generic embedded models add a lot of overhead that bloats up your data records. If you want to use them anyway, here’s how you’d do it...

In summary, try to build your models as best you can to actually match your requirements. If you know nothing about your models ahead of production, then perhaps Django isn't the right solution for you.

这篇关于从现有的MongoDB数据库创建Django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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