You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django外卖配送项目模块导入异常求助:模块已存在但无法导入City模型

Fixing the Circular Import Error in Your Django Food Delivery App

Hey there, let's break down why you're hitting this ImportError and how to fix it for good!

First off, this is a classic circular import problem—your apps are trying to import from each other at the module level, which confuses Django when it's loading all models during setup. Let's trace the loop from your error log:

  • menus/models.py imports Restraunts from restaurants.models
  • restaurants/models.py imports everything from customers.models
  • customers/models.py tries to import City from restaurants.models

Django gets stuck here: when it's loading customers models, it hasn't finished loading restaurants models yet, so City doesn't exist as far as it knows. The reason it worked before was probably a lucky one-time loading order (Django's model loading has edge cases like that), but it's never a stable solution.

Here are the best ways to fix this:

1. Use String-Based Model References (Recommended)

Instead of directly importing cross-app models, use Django's string reference syntax. This tells Django to look up the model later, after all models are fully loaded.

For example, in customers/models.py, replace this:

from restaurants.models import City

class YourCustomerModel(models.Model):
    city = models.ForeignKey(City, on_delete=models.CASCADE)

With this:

class YourCustomerModel(models.Model):
    city = models.ForeignKey('restaurants.City', on_delete=models.CASCADE)

Do the same in restaurants/models.py for any references to customers models. Replace wildcard imports like from customers.models import * with targeted string references:

class Restraunts(models.Model):
    some_customer_field = models.ForeignKey('customers.Customer', on_delete=models.CASCADE)

2. Move Shared Models to a Common App

If City is a model used by multiple apps (like restaurants and customers), consider creating a new app (e.g., common or locations) and moving City there. Then both apps can import from common.models without creating a loop.

3. Ditch Wildcard Imports

Wildcard imports like from customers.models import * are risky—they pull in more code than you need and make circular imports far more likely. Stick to importing only the specific models you need, and use string references for cross-app imports.

Once you make these changes, run python manage.py makemigrations and python manage.py migrate to sync everything up, then restart your server. This should resolve the import error permanently.

内容的提问来源于stack exchange,提问作者Atif Shafi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 22:47:37