Failed import for drf_nested_routers

this import in urls.py gives me an error

from drf_nested_routers import DefaultRouter as NestedDefaultRouter


Import "drf_nested_routers" could not be resolved

however the drf_nested_routers it is installed venv as in inside my requirements.txt file

TL;DR: Typo in package name—install drf-nested-routers (not drf_nestled_routers) and fix the import.

The "Import 'drf_nestled_routers' could not be resolved" error occurs because "nestled" is a misspelling. The correct Django REST Framework (DRF) package for nested routers is drf-nested-routers (note: "nested," not "nestled"). Python can't find non-existent modules, which is why the failure occurs.

Quick Fix Steps

  1. Install the Correct Package. In your terminal (with your virtual environment activated):

    text

    pip install drf-nested-routers
    
  2. Update the Import in urls.py. Change your import statement to:

    Python

    from drf_nested_routers import DefaultRouter as NestedDefaultRouter
    
    • This uses underscores (_) in the module name, as Python expects (hyphens in the PyPI package become underscores post-install).

    • Your alias NestedDefaultRouter works fine—feel free to keep it.

  3. Verify It Works. Run Django's shell and test:

    text

    python manage.py shell
    

    Then:

    Python

    from drf_nested_routers import DefaultRouter
    print(DefaultRouter)  # No error = success!
    

Why This Fixes It

  • PyPI package: drf-nested-routers → Installed module: drf_nested_routers.

  • A common mix-up: "Nestled" sounds similar but isn't the package name. Check PyPI for confirmation.

  • Pro tip: Use pip list | grep drf-nested to verify installation.

Extra Setup for Nested Routers in DRF

If you're setting this up for the first time, add to your urls.py:

Python

from drf_nested_routers import NestedDefaultRouter
from myapp.views import ParentViewSet, ChildViewSet

router = NestedDefaultRouter()
router.register('parents', ParentViewSet)
router.register(r'parents/(?P<parent_pk>[^/.]+)/children', ChildViewSet)

urlpatterns = router.urls

See the official GitHub docs for full examples. Also, ensure 'rest_framework' is in INSTALLED_APPS in settings.py.

If you're using this package drf-nested-routers, then your import statement is incorrect.

The GitHub repo shows that the NestedDefaultRouter class is available in the routers module of the rest_framework_nested package directory.

Therefore your import statement should look like this:

from rest_framework_nested.routers import NestedDefaultRouter

See https://github.com/alanjds/drf-nested-routers

Вернуться на верх