question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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

See original GitHub issue

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?

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
sobolevncommented, Jul 21, 2022

my_model.say_nothing() must raise an error. Proof: https://mypy-play.net/?mypy=latest&python=3.10&gist=728d3a85fa2a39bcfb911174f4a12b75

Can you please attach a reproducable example where it does not?

0reactions
UnknownPlatypuscommented, Oct 10, 2022

If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column.

Because of that, django-stubs only declare the pk attribute on models.Model and not the id 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:

TModel = TypeVar('TModel', bound=models.Model)

class SomeModel(models.Model):
    name = models.Charfield(primary_key=True)

def transform_model(some_object: TModel) -> TModel:
    LOGGER.info("Transforming model with id %s", model.id)
    return some_object

transform_model(SomeModel.objects.first()) # AttributeError: 'SomeModel' object has no attribute 'id'

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

typing — Support for type hints — Python 3.11.1 documentation
This module provides runtime support for type hints. The most fundamental support consists of the types Any , Union , Callable , TypeVar...
Read more >
Type hints cheat sheet - mypy 0.991 documentation
Type hints cheat sheet#. This document is a quick cheat sheet showing how to use type annotations for various common types in Python....
Read more >
Get started with Python type hints | InfoWorld
Use Optional to indicate that an object is either one given type or None . For example: from typing import Dict, Optional, Union...
Read more >
How do I type hint a method with the type of the enclosing class?
If you use the Django framework, this may be familiar, as Django models also use strings for forward references (foreign key definitions where...
Read more >
Type Hints in Python: What, Why, and How - YouTube
In this video I talk about annotating your functions and variables with type hints in Python and why you should do it.Need one-on-one...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found