-
Notifications
You must be signed in to change notification settings - Fork 259
Description
Describe the bug
Unable to use string references with Link
across different modules. When using string references for Link
without importing the actual model classes (i.e., relying on forward references), a ForwardRef
error is raised. This issue arises when models from different modules reference each other.
To Reproduce
Provide the following code snippet to reproduce the issue:
# users/models.py
from beanie import Document, Link
from pydantic import Field
from typing import Optional
class User(Document):
username: str = Field(unique=True, index=True)
email: str
bio: Optional[str] = None
class Settings:
name = "users"
class Profile(Document):
user: Link[User]
avatar: Optional[str] = None
favorite_post: Optional[Link['Post']] = None # Forward reference
class Settings:
name = "profiles"
# posts/models.py
from beanie import Document, Link
from pydantic import Field
from typing import List
from datetime import datetime
class Post(Document):
title: str
content: str
author: Link['User'] # Forward reference
created_at: datetime = Field(default_factory=datetime.utcnow)
class Settings:
name = "posts"
class Comment(Document):
post: Link[Post]
author: Link['User'] # Forward reference
content: str
created_at: datetime = Field(default_factory=datetime.utcnow)
class Settings:
name = "comments"
Expected behavior
When there are no circular relationships in the database schema, I expect to be able to reference models from different modules using string references (without importing them explicitly) without encountering ForwardRef
errors.
Additional context
This error occurs when defining Link
references across modules. Ideally, forward references should allow linking models without circular imports. This behavior is necessary when defining related models in separate files.