Skip to content

Proper way to write stub file for abstract models #829

Open
@miaachan

Description

@miaachan

Bug report

What's wrong

I ran into a situation where I had to write stubs for my abstract model. But, mypy
is treating the inherited fields as Any.

Setup:

# base.py
from django.db import models

class TestModelBase(models.Model):
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True
# base.pyi - stub of base.py
from django.db import models

class TestModelBase(models.Model):
    date_created: models.DateTimeField
    date_modified: models.DateTimeField
    
    class Meta:
        abstract: bool
# models.py
from django.db import models
from .base import TestModelBase

class ModelA(TestModelBase):
    own_datetime = models.DateTimeField(null=True, blank=True)

reveal_type(ModelA.date_modified) # -> OK! Revealed type is "django.db.models.fields.DateTimeField[Any, Any]"
reveal_type(ModelA.own_datetime) # -> Revealed type is "django.db.models.fields.DateTimeField[Union[builtins.str, datetime.date, django.db.models.expressions.Combinable, None], Union[datetime.datetime, None]]"

It is weird that reveal_type(ModelA.date_modified) is able to yield DateTimeField
but fails in the next case.

Interact with model:

# t.py
from .models import ModelA

class A:
    foo: ModelA

    def bar(self) -> None:
        reveal_type(self.foo) # -> Revealed type is "pg.models.ModelA"
        reveal_type(self.foo.date_modified) # -> Revealed type is "Any"
        reveal_type(self.foo.own_datetime) # -> Revealed type is "Union[datetime.datetime, None]"

If the stub base.pyi is removed, the revealed type of self.foo.date_modified becomes
normal -> Revealed type is "datetime.datetime*". Am I missing something in the stub?

How is that should be

self.foo.date_modified should be datetime.datetime instead of Any

System information

  • OS:
  • python version: 3.9.5
  • django version: 3.2.5
  • mypy version: 0.931
  • django-stubs version: 1.9.0
  • django-stubs-ext version: 0.3.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions