Skip to content

Commit 67a8899

Browse files
authored
Add docs about "type[Model] does not have objects attribute" (#2519)
Refs #1684
1 parent 91928a0 commit 67a8899

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,36 @@ reveal_type(settings.EXISTS_AT_RUNTIME) # N: Any
310310
reveal_type(settings.MISSING) # E: 'Settings' object has no attribute 'MISSING'
311311
```
312312

313+
### How to use `type[Model]` annotation with `.objects` attribute?
314+
315+
Let's say you have a function similar to this one,
316+
which accepts a model type and accesses its `.object` attribute:
317+
318+
```python
319+
from django.db import models
320+
321+
def assert_zero_count(model_type: type[models.Model]) -> None:
322+
assert model_type.objects.count() == 0
323+
```
324+
325+
This code will raise an error from mypy:
326+
327+
```
328+
error: "type[Model]" has no attribute "objects" [attr-defined]
329+
```
330+
331+
It is a common problem: some `type[models.Model]` types won't have `.objects` available.
332+
Notable example: [abstract models](https://docs.djangoproject.com/en/5.1/topics/db/models/#abstract-base-classes).
333+
See [the reasoning here](https://github.com/typeddjango/django-stubs/issues/1684).
334+
335+
So, instead for the general case you should write:
336+
337+
```python
338+
def assert_zero_count(model_type: type[models.Model]) -> None:
339+
assert model_type._default_manager.count() == 0
340+
```
341+
342+
313343
## Related projects
314344

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

0 commit comments

Comments
 (0)