Skip to content

[BUG]. Using string reference for Links is not possible #1035

@Yalchin403

Description

@Yalchin403

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions