0

When running a migration, I am currently getting this lazy reference ValueError whenever the model that I have a defined ManyToManyField is in a separate file from the model that I am targeting. However, when I place the two models in the same file, I am able to successfully run the mirgation.

  1. Why is this error happening?
  2. Is it possible to separate the models (community.py and community_member.py) into separate files?

ValueError: contains a lazy reference to fitness.communitymember, but app 'fitness' doesn't provide model 'communitymember'.

My directory structure looks like this:

my_app
  |----fitness
       |----user.py
       |----community.py
       |----community_member.py

community.py

class Community(models.Model):
    id = models.AutoField(
        primary_key=True,
    )
    owner = models.ForeignKey(
        User,
    )
    members = models.ManyToManyField(
        User,
        through='CommunityMember',
        through_fields=('community', 'member')
    )

    class Meta:
        db_table = 'Communities'

community_member.py

class CommunityMember(models.Model):
    community = models.ForeignKey(
        Community,
        db_column='community_id'
    )
    member = models.ForeignKey(
        User,
        db_column='member_id',
    )

    class Meta:
        db_table = 'Community_Members'

settings.py

INSTALLED_APPS = [
    'my_app.fitness'
]           

If I place the contents of community_members.py inside of community.py the migration is successfully executes, but I am not sure why.

Rashad
  • 235
  • 4
  • 15

1 Answers1

0

Rashed, I really don't know why you need to split your models, but if you insisted in doing so, there must be a reason. A default Django's app must include a models.py file. The ValueError comes from the fact Django is unable to find all your models definitions, it simple doesn't know where to look for these models. If you insist in doing so (which I personally don't recommend with only two models) you should do what the docummentation recommends: https://docs.djangoproject.com/en/1.11/topics/db/models/#organizing-models-in-a-package

gmacro
  • 397
  • 3
  • 6
  • Thank you @gmacro. I'm fairly new to Django, and splitting up models into multiple files is a pattern taken from other frameworks. The #organizing-models-in-a-package section in the Django docs fixed my problem. Also, I did not realize it was a Django anti-pattern to split models across different files. By default, models should live in models.py, and if not, it is recommended to create a separate app directory anyway. Thanks again. – Rashad Aug 05 '18 at 23:51
  • @Rashadm, wish you all the luck in your new "Django journey", hope you enjoy it. Django is very well documented, if you have a doubt, it's probably there. Take a look at this answer, it will help you out: https://stackoverflow.com/questions/22841764/best-practice-for-django-project-working-directory-structure – gmacro Aug 06 '18 at 01:56