簡體   English   中英

從視圖導入到Django中的模型

[英]Importing from views to models in Django

我在我的一個應用程序的models.py有這樣的東西:

class Account(AbstractBaseUser):
    email = models.EmailField(unique=True)

我想從另一個應用程序的views.py中導入一個類,如下所示:

from anotherapp.views import MyClass

問題出在anotherapp.views文件的第一行,我導入了Account類。 因此,當我想將MyClass導入到models.py文件中時,此錯誤會引發:

ImportError: cannot import name Account

這是您遇到的循環導入錯誤。 雖然從Django中的視圖導入到模型是不好的做法 ,但如果您仍然想要,可以按照此問題中的方法來解決它。

以下是幾種可以被視為良好實踐的替代方法:

  • 您可以考慮導入anotherapp存在的其他低級模塊而不是MyClass (不依賴於views.py
  • 您可以使用Django的信號來捕捉anotherapp的項目范圍,並按照行動。
  • 你可以創建第三個文件,比如在utils.py中的anotherapp ,在anotherapp移動MyClass並讓anotherapp/views.py和你的應用程序的models.pyanotherapp.utils導入

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM