Skip to content

What's the best way to write a type hint for any kind of model object? #1068

Open
@YPCrumble

Description

@YPCrumble

Thanks for maintaining this repo! I have an issue that's likely a documentation issue in that I can't figure out how to create a type hint for a django model object that supports more than one model class.

I'm writing a type hint for a function that takes a model object of any type and performs an action on it, something like:

def transform_model(some_object: models.Model) -> models.Model:
    LOGGER.info("Transforming model with id %s", model.id)  # example of an error MyPy would raise
    return some_object

The issue I'm facing is that if I try to use models.Model as my type hint, I get errors like:

"Model" has no attribute "id"

as well as an error for any model methods I'm trying to use in the transformation function.

If I use a particular model class as the type hint it works fine, for instance some_object: SomeParticularModel. The issue is that I want to use this function for any type of model, not just SomeParticularModel.

Is there an appropriate way to be able to type hint a generic Django model?

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