Django Ninja API schema circular import error
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:
GET /api/todos
- a list of tasks with related ownersGET /api/todos/{task_id}
- a task with ownerGET /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
Please let me know if you need more information.
You can check if the name of the two models or file name is the same or not if that also does not work then tell them to make a model in the same file or add that one in the same file so circular data will not happen.
Hope this will help you.