gpt4 book ai didi

python - 将models.py拆分成几个文件

转载 作者:IT老高 更新时间:2023-10-28 21:33:51 26 4
gpt4 key购买 nike

我正在尝试将我的应用的 models.py 拆分为多个文件:

我的第一个猜测是这样做:

myproject/
settings.py
manage.py
urls.py
__init__.py
app1/
views.py
__init__.py
models/
__init__.py
model1.py
model2.py
app2/
views.py
__init__.py
models/
__init__.py
model3.py
model4.py

这不起作用,然后我找到了this ,但是在这个解决方案中我仍然有一个问题,当我运行 python manage.py sqlall app1 我得到了类似的东西:

BEGIN;
CREATE TABLE "product_product" (
"id" serial NOT NULL PRIMARY KEY,
"store_id" integer NOT NULL
)
;
-- The following references should be added but depend on non-existent tables:
-- ALTER TABLE "product_product" ADD CONSTRAINT "store_id_refs_id_3e117eef" FOREIGN KEY ("store_id") REFERENCES "store_store" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "product_product_store_id" ON "product_product" ("store_id");
COMMIT;

对此我不太确定,但我担心这部分应添加以下引用,但取决于不存在的表:

这是我的 model1.py 文件:

from django.db import models

class Store(models.Model):
class Meta:
app_label = "store"

这是我的 model3.py 文件:

from django.db import models

from store.models import Store

class Product(models.Model):
store = models.ForeignKey(Store)
class Meta:
app_label = "product"

显然有效,但我在 alter table 中得到了评论,如果我尝试这个,同样的事情会发生:

class Product(models.Model):
store = models.ForeignKey('store.Store')
class Meta:
app_label = "product"

那么,我应该手动运行 alter for references 吗?这可能会给我带来南方的问题吗?

最佳答案

对于任何使用 Django 1.9 的人,现在框架都支持它而无需定义类元数据。

https://docs.djangoproject.com/en/1.9/topics/db/models/#organizing-models-in-a-package

注意:对于 Django 2,it's still the same

The manage.py startapp command creates an application structure that includes a models.py file. If you have many models, organizing them in separate files may be useful.

To do so, create a models package. Remove models.py and create a myapp/models/ directory with an __init__.py file and the files to store your models. You must import the models in the __init__.py file.

所以,在你的情况下,对于像这样的结构

app1/
views.py
__init__.py
models/
__init__.py
model1.py
model2.py
app2/
views.py
__init__.py
models/
__init__.py
model3.py
model4.py

你只需要这样做

#myproject/app1/models/__init__.py:
from .model1 import Model1
from .model2 import Model2

#myproject/app2/models/__init__.py:
from .model3 import Model3
from .model4 import Model4

关于导入所有类的注意事项:

Explicitly importing each model rather than using from .models import * has the advantages of not cluttering the namespace, making code more readable, and keeping code analysis tools useful.

关于python - 将models.py拆分成几个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6336664/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com