[Python] Django Ninja API schema circular import error

Discussão em 'Python' iniciado por Stack, Março 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have UserSchema:

    # users/models.py
    class User(AbstractUser):
    ...


    # users/schemas.py
    from typing import List
    from tasks.schemas import TaskSchema

    class UserSchema(ModelSchema):
    tasks: List[TaskSchema] = []

    class Config:
    model = User
    ...


    ...and TaskSchema:

    # tasks/models.py
    class Task(models.Model):
    ...
    owner = models.ForeignKey(User, related_name="tasks", on_delete=models.CASCASE)


    # tasks/schemas.py
    from users.schemas import UserSchema

    class TaskSchema(ModelSchema):
    owner: UserSchema

    class Config:
    model = Task
    ...


    But it throws:

    ImportError: cannot import name 'TaskSchema' from partially initialized module 'tasks.schemas' (most likely due to a circular import) (/Users/myname/codes/django/ninja-api/tasks/schemas.py)


    What I want to do is that I want to fetch:

    1. GET /api/todos - a list of tasks with related owners
    2. GET /api/todos/{task_id} - a task with owner
    3. GET /api/users/{user_id} - a user with a list of owned tasks

    Versions:

    python = ^3.11
    django = ^4.1.5
    django-ninja = ^0.20.0

    Continue reading...

Compartilhe esta Página