Skip to content

models.Model.DoesNotExist and models.Model.MultipleObjectsReturned incorrectly considered undefined #1697

@sjdemartini

Description

@sjdemartini

Bug report

What's wrong

In writing generic code that needs to handle potentially different models, it's useful to be able to catch general exceptions with:

try:
    result = queryset.get()
except models.Model.DoesNotExist:
    ...
except models.Model.MultipleObjectsReturned:
    ...

However, as of django-stubs 4.2.4 (apparently via #1663), django-stubs now claims that these generic base exception classes are not defined:

  • error: "type[Model]" has no attribute "DoesNotExist" [attr-defined]
  • error: "type[Model]" has no attribute "MultipleObjectsReturned" [attr-defined]

How is that should be

models.Model.DoesNotExist and models.Model.MultipleObjectsReturned are both real/defined exception classes that can be used and are needed/useful in generic code where the specific model class is not known.

Those attributes were apparently marked as "abstract" per comment here #1653 (comment) and are only available via django-stubs for non-abstract models, which is not technically correct and limits real-world usage of these base exception classes.

System information

  • OS: MacOS 13.5
  • python version: 3.10
  • django version: 3.2.21
  • mypy version: 1.5.0
  • django-stubs version: 4.2.4
  • django-stubs-ext version: 4.2.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions