What's the best way to write a type hint for any kind of model object?
See original GitHub issueThanks 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?
Issue Analytics
- State:
- Created a year ago
- Comments:8 (3 by maintainers)
my_model.say_nothing()
must raise an error. Proof: https://mypy-play.net/?mypy=latest&python=3.10&gist=728d3a85fa2a39bcfb911174f4a12b75Can you please attach a reproducable example where it does not?
Because of that, django-stubs only declare the pk attribute on
models.Model
and not theid
one because he might not exist. The presence of an id field will be correctly inferred if you give a more specific model.@YPCrumble I think in your case you probably want to reference the pk because if one of your models were to set the primary_key on another field, you would have a runtime error:
If nonetheless, you know for sure that every models will have an id, I’m not sure how you can declare that. I guess the pk tip should do the trick.