0

I somehow can not import my models from another app. I already looked it up and tried but does not work.

events/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)

When I run python manage.py makemigrations I get this.

Error

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'

payments/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)

What am I doing wrong?

Franz
  • 35
  • 9

1 Answers1

1

You have a circular import. In this case, you can avoid it by removing the Registration import and using the string instead:

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

Another option would be to move the Payment.objects.create() code into a signal. Note that your current save() method creates a Payment every time the registration is saved, which might not be what you want.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • I tried this before, now I get **save() prohibited to prevent data loss due to unsaved related object 'registration'.** – Franz Mar 31 '18 at 11:53
  • Just reread the error. I switch the super().save() and payments.objects.create(). Works. Thanks for help. – Franz Mar 31 '18 at 11:55