Django 2:跨应用模型导入失败且无法完成保存操作求助
Hey there, let's work through this import problem you're hitting with your Registration model. Looking at the code you shared, here are the most likely culprits and fixes to try:
1. Verify Your Payment Model Import Path
First, make sure you're importing the Payment model correctly at the top of events/models.py. Depending on which app Payment lives in:
- If
Paymentis in an app namedpayments, add this import:from payments.models import Payment - If
Paymentis in the sameeventsapp, use a relative import:from .models import Payment
Double-check that your app name is spelled correctly (Python is case-sensitive, so Payments vs payments will break imports).
2. Fix Circular Import Conflicts
If the Payment model also imports Registration (creating a circular dependency), Django will throw import errors. To fix this:
- In your
payments/models.py, replace the direct import with a string reference for the ForeignKey:class Payment(models.Model): # Use 'app_name.ModelName' instead of importing Registration directly registration = models.ForeignKey('events.Registration', on_delete=models.CASCADE) # Add your other Payment fields here
This avoids the circular loop since Django resolves the string reference dynamically at runtime.
3. Ensure the Payment App is Registered in Settings
Django can't find models from apps that aren't added to INSTALLED_APPS in your project's settings.py. Confirm the app containing Payment is listed:
INSTALLED_APPS = [ # Default Django apps... 'events', 'payments', # Add this line if it's missing ]
4. Check for Typos or Naming Errors
It sounds obvious, but typos are a common culprit:
- Make sure the model class is named
Payment(notpaymentorPayments) - Confirm the app name in your import matches the actual app directory name
5. Fix the save() Method Logic (Bonus)
While not directly an import issue, your current save() method creates a Payment before saving the Registration instance. This can cause problems because the Registration won't have a primary key yet. Update it to:
def save(self, *args, **kwargs): # Save the Registration first to generate its PK super().save(*args, **kwargs) # Now create the Payment with the saved Registration Payment.objects.create(registration=self)
内容的提问来源于stack exchange,提问作者Franz

