How to use correctly types for Django model fields with django stubs?

2.9k views Asked by At

Consider the following code fragment related to Django models:

class Machine(HasStatus):  # type: ignore
    machines: "models.Manager[Machine]" = models.Manager()
    number = models.IntegerField(verbose_name="Číslo stroje", unique=True)
    #Type of "number" is "IntegerField[Unknown, Unknown]"

    class Meta: #"Meta" overrides symbol of same name in class "HasStatus"
        verbose_name = "Machine"

I was able to find out how to annotate Manager, but I don't know how to satisfy PyLance for model fields and Meta class. For the model fields, it seems I need to provide two types, but I have no idea which is the second.

Please, provide examples of how to use type annotation for more Django model fields like ForeignKey and others.

1

There are 1 answers

0
Fran On

It is not possible to correctly type models in Django, at least I know.

The issue is that django itself is not typed, and pylance uses pyright type checker, which does not use runtime information, just static analysis of the code to lint it. Mypy, on the other hand, supports plugins, and there is a plugin for Django that extracts runtime information about your models, even for dynamic model references.

Maybe in a later release thei add support for these features.