Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Queryset: TypeError: 'type' object is not subscriptable #146

Closed
sobolevn opened this issue Aug 26, 2019 · 5 comments
Closed

Queryset: TypeError: 'type' object is not subscriptable #146

sobolevn opened this issue Aug 26, 2019 · 5 comments
Labels
bug Something isn't working documentation

Comments

@sobolevn
Copy link
Member

Code:

# -*- coding: utf-8 -*-

from django.db.models.query import QuerySet

from server.apps.main.models import BlogPost


def published_posts() -> QuerySet[BlogPost]:
    """Returns published blog posts."""
    return BlogPost.objects.filter(
        is_published=True,
    )

Output:

» python manage.py runserver
2019-08-26 08:32:24 [INFO] Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Users/sobolev/.pyenv/versions/3.7.4/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/Users/sobolev/.pyenv/versions/3.7.4/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check
    include_deployment_checks=include_deployment_checks,
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks
    return checks.run_checks(**kwargs)
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 398, in check
    for pattern in self.url_patterns:
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 579, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/sobolev/Desktop/django_stubs_example/.venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 572, in urlconf_module
    return import_module(self.urlconf_name)
  File "/Users/sobolev/.pyenv/versions/3.7.4/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/sobolev/Desktop/django_stubs_example/server/urls.py", line 21, in <module>
    from server.apps.main import urls as main_urls
  File "/Users/sobolev/Desktop/django_stubs_example/server/apps/main/urls.py", line 6, in <module>
    from server.apps.main.views import BlogPostViewset, index
  File "/Users/sobolev/Desktop/django_stubs_example/server/apps/main/views.py", line 7, in <module>
    from server.apps.main.logic import repo
  File "/Users/sobolev/Desktop/django_stubs_example/server/apps/main/logic/repo.py", line 8, in <module>
    def published_posts() -> QuerySet[BlogPost]:
TypeError: 'type' object is not subscriptable

Reproduction: https://github.com/sobolevn/django_stubs_example

Fix:

def published_posts() -> 'QuerySet[BlogPost]':
    ...

I guess that it is related to #144 and also should be just documented properly.
Because for now it might cause a confusion for newcomers.

@sobolevn sobolevn added bug Something isn't working documentation labels Aug 26, 2019
@MarcinWieczorek
Copy link
Contributor

Any update on this?

@mkurnikov
Copy link
Member

Short term fix:

  • for annotations - wrap with string, as mentioned by @sobolevn
  • for subclassing -
class MyManager(models.Manager):
    pass
class MyModel(models.Model):
    objects = MyManager()

if you have this code (models.Manager is the same as models.Manager[Any]), plugin should perform some magic so that actual objects class will have the correct generic Manager[MyModel].

Long term fix:
vote, push core-devs, add comments under django/deps#65 (comment)

We really need to document this stuff...

@MohGanji
Copy link

Short term fix:

  • for annotations - wrap with string, as mentioned by @sobolevn

To make it easier to access, this means doing like this:

def published_posts() -> 'QuerySet[BlogPost]:'
    pass

@antonio-antuan
Copy link

I can suggest a hack that helped me:

T = TypeVar('T', bound='BaseUser')
if TYPE_CHECKING:

    _UserManager = BaseUserManager
else:

    class FakeGenericMeta(BaseUserManager.__class__):  # TODO hack, will be deleted with django 3.1
        def __getitem__(self, item):
            return self

    class _UserManager(BaseUserManager, metaclass=FakeGenericMeta):
        pass


class UserManager(_UserManager[T]):
    pass

class BaseUser(AbstractBaseUser):
    objects: UserManager[BaseUser] = UserManager()
...

@flaeppe
Copy link
Member

flaeppe commented Sep 24, 2023

QuerySet has had subscriptable support for quite some time

@flaeppe flaeppe closed this as completed Sep 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working documentation
Development

No branches or pull requests

6 participants