0

I understand that if I want to establish a foreign key relationship for this model:

class MyModel(models.Model):
    pass

... from this location

/myproject
    /myapp
       models.py (MyModel)

... I can use a "string-named" relationship to avoid import-time errors.

# this is in a different app within myproject

class DependentModel(models.Model):
    my_model = models.ForeignKey('mayapp.MyModel')

But how do I establish that same ForeignKey relationship with a string when my models have been distributed across a models dir (e.g. not contained within one models.py file)

/myproject
    /myapp
       /models
           /one.py (MyModel)
           /two.py (other models)

(Assume that I can't just import the model directly, ala from myapp.models.one import MyModel)

Quentin Donnellan
  • 2,687
  • 1
  • 18
  • 24

1 Answers1

2

Aha! I should have taken just a couple more minutes to search; this is possible simply by importing your models from within the __init__.py file inside the models dir:

# myproject/myapp/models/__init__.py

from one import MyModel

Related question: How do I separate my models out in django?

Community
  • 1
  • 1
Quentin Donnellan
  • 2,687
  • 1
  • 18
  • 24