简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM