Skip to content

Restore ability to instantiate, access objects manager, of abstract models #1653

Closed
@intgr

Description

@intgr

Continuing the discussion started at #1649 (comment)

There are two similar use cases affected by two different PRs:

Since the changes in #1393, django-stubs will raise errors on some kinds of generic code that handles abstract models. For example:

# models.py
from typing import TypeVar
from django.db import models
from django_stubs_ext.db.models import TypedModelMeta

class Animal(models.Model):
    name = models.CharField(max_length=100)

    class Meta(TypedModelMeta):
        abstract = True

class Cat(Animal):  # Concrete model
    pass

def create_animal(klass: type[Animal], name: str) -> Animal:
    obj = klass(name=name)
    obj.save()
    return obj

T = TypeVar("T", bound=Animal)

def create_animal_generic(klass: type[T], name: str) -> T:
    return klass.objects.create(name=name)

# Usage example:
# create_animal(Cat, "Garfield")
# create_animal_generic(Cat, "Grumpy")

These two functions are allowed and work with django-stubs 4.2.3. Function create_animal causes errors in git master version of django-stubs:

apidoc/models.py:16:11: error: Cannot instantiate abstract model "Animal"  [misc]

But after the unmerged changes in PR #1649, the second function create_animal_generic will also start failing:

models.py:16:11: error: Cannot instantiate abstract model "Animal"  [misc]
models.py:23:12: error: Cannot instantiate abstract model "Animal"  [misc]
models.py:23:12: error: Incompatible return value type (got "Animal", expected "T")  [return-value]

System information

  • python version: 3.11.4
  • mypy version: 1.4.1
  • django-stubs version: 4.2.3 / git

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingregressionBehavior has changed for worse with a release

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions