Django 2:无法导入模型并保存它

时间:2018-03-31 11:44:59

标签: python django-2.0

我无法从其他应用程序导入我的模型。我已经查了一下但尝试了但是没有用。

事件/ models.py

class Registration(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    team = models.CharField(max_length=50, blank=True)
    date_created = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        payment = Payment.objects.create(registration=self)
        super().save(*args, **kwargs)

当我运行python manage.py makemigrations时,我得到了这个。

错误

File "C:\Users\Rubber\ems\events\models.py", line 5, in <module>
   from payments.models import Payment   
File "C:\Users\Rubber\ems\payments\models.py", line 6, in <module>
   from events.models import Registration 
ImportError: cannot import name 'Registration'

付款/ models.py

import uuid

from django.db import models
from django.utils import timezone

from events.models import Registration  # THIS WONT WORK


def _create_uuid():
    return uuid.uuid1()

def _get_uuid():
    return _create_uuid()

class Payment(models.Model):
    uuid = models.CharField(max_length=1, default=_get_uuid)
    paid = models.BooleanField(default=False)
    registration = models.ForeignKey(Registration, on_delete=models.CASCADE)

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您有循环导入。在这种情况下,您可以通过删除Registration导入并使用字符串来避免它:

class Payment(models.Model):
    registration = models.ForeignKey('events.Registration', on_delete=models.CASCADE)

另一种选择是将Payment.objects.create()代码移到signal。请注意,您当前的save()方法会在保存注册的每个时创建Payment ,这可能不是您想要的。