Sharing models between Django apps

ⅰ亾dé卋堺 提交于 2019-11-30 07:19:26

问题


I will be brief: to work in the spirit and idea of a Django app, it is ok for an app to import models from inside another app ? Say, a User statistics app will import models from a User app something like: from users.models import users


回答1:


If you're building an internal app that has no chance of ever being released to the public, sure, do whatever you want.

If you're building an internal app that has little chance of ever being released to the public, but will possibly be used by future/current developers, sure, but be sure to document what the app needs to work properly.

If you're building an app for public release, try to keep it self-dependent (and django-internals dependent, ie, use what django provides, when possible). If you really need a third-party app to work, or if a third party app would make your code more manageable, then sure, include dependencies, but be doubly sure to document all requirements and necessary setup.

In most cases, you can do almost whatever you want so long as you have sufficient documentation.

I do, however, have to question the sanity of making your own User model that has the same name as django's builtin auth.User.




回答2:


The answer is yes. It's perfectly okay for one application inside your django project to import models from another application. The power of a django project lies in the apps and their interactions.

Also make sure that you have utility applications importing models from more generic applications and not the other way. So "userstatistics" app should import models from the "users" app but "users" app should not rely on the "userstatistics".

If your app is importing models from a 3rd party application (lets say django-piston), be sure to specify that in a requirements file.




回答3:


You cand try better extending the Django User model with inheritance. You will use the django user with custom field added, so you will have the same user for all the apps.




回答4:


Don't do this. They will have the same app name and the ORM will be confused. Use an abstract model instead, and have both derive from it.



来源:https://stackoverflow.com/questions/4137287/sharing-models-between-django-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!