django-stubs icon indicating copy to clipboard operation
django-stubs copied to clipboard

`MyField(models.CharField)` not handled as `str` (but `Any`)

Open blueyed opened this issue 4 years ago • 2 comments

Given t_derived_model.py:

from django.db import models


class MyField(models.CharField):
    pass


class MyModel(models.Model):
    myfield = MyField()
    field = models.CharField()


m = MyModel()
reveal_type(m.field)
reveal_type(m.myfield)

mypy t/t_derived_modelfield.py results in:

t/t_derived_modelfield.py:14: note: Revealed type is 'builtins.str*'
t/t_derived_modelfield.py:15: note: Revealed type is 'Any'

I.e. the type of MyField is not handled like when using modfels.CharField directly.

System information

  • OS: Arch Linux
  • python version: 3.9.9
  • django version: 3.2
  • mypy version: 0.910
  • django-stubs version: 1.9.0-22-ge5361f1 (current master)
  • django-stubs-ext version: -

blueyed avatar Dec 07 '21 14:12 blueyed

It can be fixed using class MyField(models.CharField[str, str]) (giving the set-/get-type there). Would it be possible to make it default to this? Related code: https://github.com/typeddjango/django-stubs/blob/e5361f1e043f16363263319ed2de6b81bbb67ccd/django-stubs/db/models/fields/init.pyi#L261-L263

At least it is possible to force specifying it via mypy's disallow_any_generics = True, where it then results in an error without giving _ST, _GT: Missing type parameters for generic type "CharField" [type-arg]

(it also needs djangi_stubs_ext then, see https://github.com/typeddjango/django-stubs/issues/285#issuecomment-987972198)

blueyed avatar Dec 07 '21 14:12 blueyed

Yes, specifying default types for the generics would be very helpful.

I am seeing type of "{column}" is partially unknown errors for every field with basedpyright. To fix it I would have to explicitly specify the default __get__ and __set__ types for every column.

matt-allan avatar Nov 07 '25 22:11 matt-allan