I've run into this problem a few times in different situations but my setup is the following:
I have two Django models files. One that contains User models and CouponCodes that a user can use to sign up for a Course. Those are both in the account/models.py file. Course and the related many-to-many field are in a different models file, course/models.py. I usually refer to these in my code as amod and cmod respectively.
In course/models.py I have an import statement:
from account import models as amod
class Course(ExtendedModel):
stuff = stuff
I need to import the account/models.py file for the many-to-many model/table between Course and User which is not shown here. So far, so good.
In the account/models.py file I have the CouponCode model. Each instance gets created and then can be assigned to a particular Course object after creation to allow a student to use it to sign up for a course in the system.
class CouponCode(ExtendedModel):
assigned_course = UniqueIDForeignKey("course.Course", blank=True, null=True, related_name='assigned_coupon_code_set')
...
...
@staticmethod
def assign_batch(c, upper_limit):
import course.models as cmod # Why is this allowed here?
assert isinstance(c, cmod.Course)
# Do other stuff here
That static method allows me to pass in a course object and a number of CouponCodes that I want to assign to it and then it will assign the next N number of unassigned codes to that course. My question arises from the assert statement.
I need to import the Course object from course/models.py in order to insure that the object being passed in is actually an instance of Course, but if I do that at the top of the file, I get problems because this file is already being imported into course/models.py. (amod is being imported into cmod and then in amod I need to import cmod).
Why does it allow me to do this if I import it in the method right before I need it versus at the top of the file?