pythondjangovisual-studio-codedjango-models

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?


Solution

  • 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