在定義django模型外鍵的時(shí)候,如果關(guān)聯(lián)的表在另一個(gè)app內(nèi),那么有兩種定義方式:
新手常用的方法是
from production.models import Manufacturer
class Car(models.Model):
manufacturer = models.ForeignKey(
Manufacturer, #盡量避免這樣定義
on_delete=models.CASCADE,
)
官方更推薦的是如下的方式
class Car(models.Model):
manufacturer = models.ForeignKey(
'production.Manufacturer', #這樣定義比較好
on_delete=models.CASCADE,
)
原因
第二種方法能夠避免循環(huán)引用. 以上面為例炕淮,如果在production應(yīng)用下存在
# production/models.py
from vehicle.models import xxx
同時(shí)乖寒,在vehicle應(yīng)用下存在
# vehicle/models.py
from production.models import yyy
那么python就會(huì)報(bào)引用錯(cuò)誤
[ImportError: Cannot import name X]
而用第二種方法代芜,就能避免這個(gè)問題退子。