[英]Django Splitting models from models.py file
我試圖將所有模型與models.py
分開。我正在做的是在這個鏈接中提到的。 但問題是我的一個模型是django.contrib.auth.user
,我在models.py中按如下方式生成一個函數來生成令牌。
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
那么如何在_init_.py
文件中導入該東西,因為我們將模型導入為
from myapp.models.foo import Foo
你應該只有models.py
或models/__init__.py
,看起來你們兩個都有。 其中一個模塊可能會影響另一個模塊,所以不要兩者兼顧(即擺脫models.py
)
如果我正確地關注了您的問題,則無需將User
導入__init__.py
。 您只需要在聲明create_user_profile
的文件中導入它。 導入本身是標准的:
from django.contrib.auth.models import User
您無法導入命令,但是例如導入上面定義的函數,可確保運行connect調用。 models.py文件正文中的函數調用也執行相同的raeson(即導入模型)。
# p.py:
print "hello" # a command executed while importing anything
def x(): # a definition that can be imported
pass
# python shell
>>> from p import x
hello
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.