skip to Main Content

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?

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search