Reputation: 358
I have helper function for Django views that looks like this (code below). It returns None or single object that matches given query (e.g. pk=1
).
from typing import Type, Optional
from django.db.models import Model
def get_or_none(cls: Type[Model], **kwargs) -> Optinal[Model]:
try:
return cls.objects.get(**kwargs)
except cls.DoesNotExist:
return None
Supose I have created my own model (e.g. Car
) with its own fields (e.g. brand
, model
). When I asign results of get_or_none
function to a varibale, and then retriveing instance fields, I get annoying warning in PyCharm of unresolved reference.
car1 = get_or_none(Car, pk=1)
if car1 is not None:
print(car1.brand) # <- Unresolved attribute reference 'brand' for class 'Model'
What's the propper type hinting to get rid of this warning and get code completion for variable)?
Upvotes: 8
Views: 3937
Reputation: 358
Found this answer to almost simmilar question. The solution is to use TypeVar from typing
from typing import TypeVar, Type, Optional
from django.db.models import Model
T = TypeVar('T', bound=Model)
def get_or_none(cls: Type[T], **kwargs) -> Optional[T]:
... # same code
And everything works fine: no warnings and code completion
Upvotes: 7