I'm writing a todo app using flask and mongoDB and Pymodm as an ODM. I have two models named User and UserGroups. these two reference each other like so:
user.py
from api.models.userGroup import group
class User(MongoModel):
_id = fields.IntegerField(primary_key=True)
email = fields.CharField()
password = fields.CharField()
createdAt = fields.DateTimeField(default=datetime.datetime.now())
groups = [fields.ReferenceField('group')]
personalTodoLists = fields.EmbeddedDocumentListField('list')
userGroup.py
from api.models.user import user
class UserGroup(MongoModel, EmbeddedMongoModel):
_id = fields.IntegerField(primary_key=True)
name = fields.CharField()
createdAt = fields.DateTimeField(default=datetime.datetime.now())
ownerId = fields.ReferenceField('user')
contributors = [fields.ReferenceField('user')]
todoLits = fields.EmbeddedDocumentListField('list')
I'm getting the error: "ImportError: cannot import name 'user'"
How can i make references in this case properly?
Circular reference is a common problem with many-to-many relationships. The usual solution implemented by the packages is to provide you with a way to refer to (yet to be defined) other model using a string with its name, instead of the object itself.
I can see that's what you've done, actually. Eg:
groups = [fields.ReferenceField('group')]
There should be no need for you to actually import those models, then. Just comment out/remove the offending import lines, and it should work.