Skip to content

Document custom field typing #2578

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 23, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,60 @@ def assert_zero_count(model_type: type[models.Model]) -> None:
```


### How to type a custom `models.Field`?

> [!NOTE]
> This require type generic support, see <a href="#i-cannot-use-queryset-or-manager-with-type-annotations">this section</a> to enable it.


Django `models.Field` (and subclasses) are generic types with two parameters:
- `_ST`: type that can be used when setting a value
- `_GT`: type that will be returned when getting a value

When you create a subclass, you have two options depending on how strict you want
the type to be for consumers of your custom field.

1. Generic subclass:

```python
from typing import TypeVar, reveal_type
from django.db import models

_ST = TypeVar("_ST", contravariant=True)
_GT = TypeVar("_GT", covariant=True)

class MyIntegerField(models.IntegerField[_ST, _GT]):
...

class User(models.Model):
my_field = MyIntegerField()


reveal_type(User().my_field) # N: Revealed type is "int"
User().my_field = "12" # OK (because Django IntegerField allows str and will try to coerce it)
```

2. Non-generic subclass (more strict):

```python
from typing import reveal_type
from django.db import models

# This is a non-generic subclass being very explicit
# that it expects only int when setting values.
class MyStrictIntegerField(models.IntegerField[int, int]):
...

class User(models.Model):
my_field = MyStrictIntegerField()


reveal_type(User().my_field) # N: Revealed type is "int"
User().my_field = "12" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
```

See mypy section on [generic classes subclasses](https://mypy.readthedocs.io/en/stable/generics.html#defining-subclasses-of-generic-classes).

## Related projects

- [`awesome-python-typing`](https://github.com/typeddjango/awesome-python-typing) - Awesome list of all typing-related things in Python.
Expand Down
Loading