1

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.

4
  • django-stubs ships with mypy plugin that does a lot of heavy work, including field types resolution. It will not work with other type checkers, unfortunately, because plugin API is not consistent (or even does not exist) in other checkers. For mypy, see readme section. For other checkers, you can try django-types - I have never used it, but the main goal of this project is exactly removing mypy dependency, Commented Jun 9, 2022 at 10:03
  • What I am trying to find out is at least what types are supposed to be in IntegerField[Unknown, Unknown]. I could write IntegerField[int, int], but I am not sure about the second type or if my guess is even correct for the first one. Commented Jun 9, 2022 at 10:52
  • 1
    It will not work anyway. They are not simply generic. Generic signature is Field[SetType, GetType]. I'd suggest you to read doctring [here[(github.com/typeddjango/django-stubs/blob/master/django-stubs/db/…) about field typing in django-stubs. With plugin you do not need to annotate field on assignment at all, this type is inferred. Commented Jun 9, 2022 at 11:00
  • This is actually quite helpful. I was not able to find their meanings. Now it is clearer to me. Thank you. Commented Jun 9, 2022 at 11:18

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.