Swix
Swix

Reputation: 2123

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:

  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

Upvotes: 0

Views: 443

Answers (1)

August Infotech
August Infotech

Reputation: 15

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.

Upvotes: 0

Related Questions