Django - VS Code - custom model manager method typing

I'm trying custom model managers to add annotations to querysets.
My problem, which started as a little annoyance but I now realize can be an actual problem, is that VS Code does not recognise the methods defined in the custom model manager/queryset.

Example:

from django.db import models
from rest_framework.generics import ListAPIView


# models.py
class CarQuerySet(models.QuerySet):
    def wiht_wheels(self): # NOTE: intentional typo
        pass # assume this does some annotaion


class Car(models.Model):
    objects = CarQuerySet.as_manager()


# views.py
class ListCarsView(ListAPIView):
    def get_queryset(self):
        return Car.objects.wiht_weels()  # <--- white instead of yellow

At first, I was just annoyed by the fact that wiht_weels is printed in white as opposed to the usual yellow for methods/functions.

Then I was more annoyed because this means VS Code will not give me any hints as to what args the method expects or what it returns.

Finally, I accidentally made a typo on a name of one of these custom model methods, I hit refactor->rename, but it only renamed it in place, not on the places where it is used (views), probably because VS Code doesn't understand that method is being used anywhere.

Is there a solution to this?

You will have to explicitly provide type hints.

# views.py
class ListCarsView(ListAPIView):
    def get_queryset(self):
        objects: CarQuerySet = Car.objects # Type hint
        return objects.with_wheels()  # yellow

Here are some recommendations may help you

  1. Try adding type hints in to your custom methods.
  2. Configure VS Code's Python environment to use the language server Pylance.
  3. You can use Django-specific extensions to improve VS Code's understanding of Django models and querysets.

If you need then I can help you with setting up Pylance, by adding type hints to your code, or helping you to use Django-specific extensions to improve your workflow in VS Code.

I hope this will help you

Add a few type annotations to your class methods:


from django.db import models
from rest_framework.generics import ListAPIView


# models.py
class CarQuerySet(models.QuerySet):

    def with_wheels(self) -> "CarQuerySet":  # quotes here
        pass


class CarManager(models.Manager):

    def get_queryset(self) -> CarQuerySet:  # update the definition here
        return CarQueryset(self.model, using=self._db)

    def with_wheels(self) -> CarQuerySet:  # redefine method here
        return self.with_wheels(self):


class Car(models.Model):
    objects: CarManager = CarManager  # add a type hint here

vs code will now show you your customer queryset methods anytime you invoke them from the Car model:

Car.objets.with...   # try this
Back to Top